def hide_image(public_img, secret_img):
	s=4
	#the bits we are going to overwrite
	data = Image.open(public_img)
	#the bits we are going to write
	key  = ImageOps.autocontrast(Image.open(secret_img).resize(data.size))
	for x in range(data.size[0]):
		for y in range(data.size[1]):
			p = data.getpixel((x, y))
			q = key.getpixel((x, y))
			red   = p[0] - (p[0] % s) + (s * q[0] / 255)
			if(x > 200 and x < 206 and y > 200 and y < 206):
				print(p[0] - (p[0] % s) + (s * q[0] / 255),
					p[1] - (p[1] % s) + (s * q[1] / 255),
					p[2] - (p[2] % s) + (s * q[2] / 255))
				# print('p[0], q[0]')
				# print(p[0], q[0])
				# print('p[1],q[1]')
				# print(p[1],q[1])
				# print('p[2],q[2]')
				# print(p[2],q[2])
			green = p[1] - (p[1] % s) + (s * q[1] / 255)
			blue  = p[2] - (p[2] % s) + (s * q[2] / 255)
			data.putpixel((x,y), (red,green,blue))
			# if (red > 100 and green < 100 and blue < 100):
				# print('x,y')
				# print(x, y)
				# print('Cover IMG, Hide Image')
				# print(p,q)
				# print('R,G,B')
				# print(red,green,blue)
	return data
Esempio n. 2
0
 def __init__(self):    
     self.fielddata = []
     #image load
     self.fieldimg = Image.open("field3.jpg")
     self.puyoimg = Image.open("puyo.gif")
     w=self.puyoimg.size[0]/6
     h=self.puyoimg.size[1]/18
     self.colorpuyo=[]
     curw=0
     curh=0
     idx =0
     while idx<=5:
         tmp=[]
         curh=0
         while curh<self.puyoimg.size[1]:
             im = self.puyoimg.crop((curw,curh,curw+w,curh+h))
             im=im.convert("RGBA")
             tmp.append(im)
             curh+=h
         self.colorpuyo.append(tmp)
         idx+=1
         curw+=w
     #trans init
     self.colortoint={"R":0,"B":1,"Y":2,"G":3,"P":4,"O":5}
     #up right down left
     #1,2,4,8
     self.dxy=[[0,-1],[1,0],[0,1],[-1,0]]
     self.dconidx=[1,2,4,8]
     """
     0,1,4,5,8,9,12,13,2,3,6,7,10,11,14,15
     """
     self.connectpattern={0:0,1:1,4:2,5:3,8:4,9:5,12:6,13:7,2:8
                 ,3:9,6:10,7:11,10:12,11:13,14:14,15:15}
Esempio n. 3
0
def load(n=None):
    try:
        if not n:
            n = nlist[randint(0,J)]
        im = Image.open(pjoin(basedir, "dinocomics%06i.png"%n))
        wxtest = piltowx(im) # error Interlaced PNGs
        # print n,fromimage(im).shape
        # assert(fromimage(im).shape == (500,735,3)), "Not the right shape"
        # print im.size
        while im.size != (735,500): # ignore wrong sized images (guest comics)
            # print im.size
            # copyPanel(load(1),im,2)
            n = nlist[randint(0,J)]
            im = Image.open(pjoin(basedir, "dinocomics%06i.png"%n))
            wxtest = piltowx(im)
        return im
        # except AssertionError
    except Exception, e:
        print "Load Error: %i"%n,e
        # import sys
        # sys.exit()
        # if n < J:
        n = n%nlist[-1]
        time.sleep(1)
        return load(n+1)
Esempio n. 4
0
def compare_images(file1, file2):
    """
    Compare two images, pixel by pixel, summing up the differences in every
    component and every pixel.  Return the magnitude of the difference between
    the two images.

        file1: A path to the first image file on disk
        file2: A path to the second image file on disk
    """

    img1 = Image.open(file1)
    img2 = Image.open(file2)

    if img1.size[0] != img2.size[0] or img1.size[1] != img2.size[1]:
        raise ValueError("Images are of different sizes: img1 = (" +
                         str(img1.size[0]) + " x " + str(img1.size[1]) +
                         ") , img2 = (" + str(img2.size[0]) + " x " +
                         str(img2.size[1]) + ")")

    size = img1.size

    img1 = img1.load()
    img2 = img2.load()

    indices = itertools.product(range(size[0]), range(size[1]))
    diff = 0

    for i, j in indices:
        p1 = img1[i, j]
        p2 = img2[i, j]
        diff += abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) + abs(p1[2] - p2[2])

    return diff
Esempio n. 5
0
def generate_diff(img1, img2):
    _img1 = Image.open(img1)
    _img2 = Image.open(img2)
    #return ImageChops.blend(_img1, _img2, 0.5)
    #return ImageChops.difference(_img1, _img2)
    bld = Image.blend(_img1, _img2, 0.5)
    return Image.composite(_img1, _img2, bld)
def TestD():
	i1 = np.array(Image.open("test_inputs/checker.jpg").convert('L'),dtype="float")
	i2 = np.array(Image.open("test_inputs/checker_grad.jpg").convert('L'),dtype="float")
	i3 = np.array(Image.open("test_inputs/checker_blur.jpg").convert('L'),dtype="float")
	
	i1Norm = norm(i1)
	i2Norm = norm(i2)
	i3Norm = norm(i3)
	
	d11 = d(i1,i1,i1Norm,i1Norm)
	d22 = d(i2,i2,i2Norm,i2Norm)
	print "\nd(i1,i1) =", d11
	print "d(i2,i2) =", d22

	# test2: symmetry
	d12 = d(i1,i2,i1Norm,i2Norm)
	d21 = d(i2,i1,i2Norm,i1Norm)
	print "\nd(i1,i2) =", d12
	print "d(i2,i1) =", d21

	# test3: triangle inequality
	d23 = d(i2,i3,i2Norm,i3Norm)
	d13 = d(i1,i3,i1Norm,i3Norm)
	print "\nd(i1,i2) =", d12
	print "d(i2,i3) =", d23
	print "d(i1,i3) =", d13
	print "d(i1,i3) =< d(i1,i2) + d(i2,i3)"
	print "d(i1,i3) >= abs(d(i1,i2) - d(i2,i3))"
	print abs(d12 - d23), "<=", d13, "<=", d12 + d23, "\n"
Esempio n. 7
0
def getTemplate(img_test):
    im1 = Image.open('Template1/0130')
    im2 = Image.open('Template1/3214')
    im3 = Image.open('Template1/7564')
    im4 = Image.open('Template1/7849')
    bw_im1 = im1.convert('1')
    bw_im2 = im2.convert('1')
    bw_im3 = im3.convert('1')
    bw_im4 = im4.convert('1')
    #bw_im1 = numpy.ndarray(im1)
    dic_0 = np.asarray(bw_im1.crop((0,0,10,10)))
    dic_1 = np.asarray(bw_im1.crop((10,0,20,10)))
    dic_2 = np.array(bw_im2.crop((10,0,20,10)))
    dic_3 = np.array(bw_im2.crop((0,0,10,10)))
    dic_4 = np.array(bw_im2.crop((30,0,40,10)))
    dic_5 = np.array(bw_im3.crop((10,0,20,10)))
    dic_6 = np.array(bw_im3.crop((20,0,30,10)))
    dic_7 = np.array(bw_im3.crop((0,0,10,10)))
    dic_8 = np.array(bw_im4.crop((10,0,20,10)))
    dic_9 = np.array(bw_im4.crop((30,0,40,10)))
    Dict = [dic_0,dic_1,dic_2,dic_3,dic_4,dic_5,dic_6,dic_7,dic_8,dic_9]
    
    dic_0 = np.asarray(dic_0, dtype='bool')
    dic_1 = np.asarray(dic_1, dtype='bool')
    a = dic_0^dic_1
    b = [dic_0,dic_1]
    c = b[0]
    dic_2 = np.asarray(dic_2, dtype='int32')
    
    img_test = img_test.convert('1')
    for i in range(4):
        subImg = img_test.crop((i*10,0,(i+1)*10,10))
Esempio n. 8
0
def make_tile(fname,out,rot=0):
	image = prep_image(fname)
	image = image.rotate(rot,expand=1)

	# chop added extra pixels by expanding
	d = quality*4
	dx,dy = image.size
	image = image.crop((d,d,dx-d,dy-d)).copy()

	# Scale Y-axis
	# convert -resample is much better than PIL.
	# ideally we'd use GIMP ...
	image.save("in.png")
	os.system("convert in.png -resample %dx%d  out.png" % (size[0]*quality,size[1]*quality))
	image = Image.open("out.png")

	# Apply tilemask
	w,h = image.size
	tmask,imask = make_tilemasks((w,h))
	tile = Image.new("RGBA",(w,h),(0,0,0,0))
	tile.paste(image,tmask)

	# Again convert -resize is better ...
	tile.save("in.png")
	os.system("convert in.png -resize %dx%d out.png" % (size))
	image = Image.open("out.png")
	image.save(out)
Esempio n. 9
0
def main():
    pool = multiprocessing.Pool() # For the parallel map()
    if sys.argv[1] == "decode":
        source = Image.open(sys.argv[1])
        print ("Decoding the encoded...")
        secret = decode (sys.argv[1], 3, 2, 3)
        output = Image.new("L", source.size)
        output.putdata(secret)
        output.save(sys.argv[2])
    elif sys.argv[1] == "encode":
        im = Image.open(sys.argv[1])
        print ("Chopping Bits...")
        secret = hidden(sys.argv[1])
        print ("Cooking the Pot...")
        messenger = carrier(sys.argv[2])
        print ("Potting the Bits...")
        final = zip (secret, messenger)
        # In the first versions the variables used a disproportionate amount of
        # RAM
        del (secret)
        del (messenger)
        final = list (pool.map (add, final))
        final = list (pool.map (tuple, final))
        output = Image.new("RGB",im.size)
        output.putdata(final)
        output.save(sys.argv[3])
Esempio n. 10
0
 def visit_image(self, node):
     ''' EMPTY
         uri       CDATA     #REQUIRED
         alt       CDATA     #IMPLIED
         height    NMTOKEN   #IMPLIED
         width     NMTOKEN   #IMPLIED
         scale     NMTOKEN   #IMPLIED
     '''
     attrs = node.attributes
     # TODO: scale
     uri = node.attributes['uri']
     try:
         img = Image.open(uri)
     except IOError:
         uri = uri[3:]
         img = Image.open(uri)
     w, h = img.size
     print '%dx%d %s' % (w, h, uri)
     if h > 420:
         nw = int((w * 420) / float(h))
         nh = 420
     else:
         nw, nh = w, h
     self.w('<image filename="../%s" width="%d" height="%d" />' %
         (uri, nw, nh))
Esempio n. 11
0
def main(argv):
    """
    main loop
    """
    for arg in argv:
        print arg
    if argv[1] == '-f':
        try:
            image = Image.open(ABSFILEPATH + '/' + argv[2])
            blogsize(image, argv[2])
            image.show()
        except Exception:
            print 'cant open'
    elif argv[1] == '-blog':
        for  name in os.listdir(os.getcwd()):
            try:
                if name[-3:] == 'jpg' or name[-3:] == 'JPG' :
                    image = Image.open(ABSFILEPATH + '/' + name)
                    blogsize(image, name)
            except Exception:
                pass        
    elif argv[1] == '-flickr':
        #for root,dirs,files in os.walk(ABSFILEPATH.join(argv[1])):
        for name in os.listdir(os.getcwd()):
            try:
                if name[-3:] == 'jpg' or name [-3:] == 'JPG' :
                    image = Image.open(ABSFILEPATH + '/' + name)
                    flickrsize(image, name)
            except Exception:
                pass
    else:
        print 'unknown parameter!'
def procesamiento_imagen():    
	## Convertir a grayscale
	img = Image.open(rostro).convert('LA')
	img.save('greyscale.png')

	## Resize

	foo = Image.open("greyscale.png")
	foo = foo.resize((256,256),Image.ANTIALIAS)
	foo.save("greyscale.png",optimize=True,quality=95)	


	##  Eliminar ruido
	img = cv2.imread('greyscale.png')
	dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)

	## Canny detector
	img = cv2.imread('greyscale.png',0)
	edges = cv2.Canny(img,256,256)

	plt.subplot(121),plt.imshow(img,cmap = 'gray')
	plt.title('Original Image'), plt.xticks([]), plt.yticks([])
	plt.subplot(122),plt.imshow(edges,cmap = 'gray')
	plt.title('Edge Image'), plt.xticks([]), plt.yticks([])

	plt.show()
def s2i(jsonsig, input_image=BLANK_IMAGE, pincolor=(0,0,255),
        force_no_sig_image=False, nosig_image=NO_SIG_IMAGE):
    
      
    if force_no_sig_image==True:
        im = Image.open(nosig_image)
        return im
    #Decode valid json or return None
    try:
        l=json.loads(jsonsig)
    except(exceptions.ValueError):
        im = Image.open(nosig_image)
        return im
    #Make sure its a signature or return None
    if not l[0].has_key('lx') or not l[0].has_key('my'):
        im = Image.open(nosig_image)
        return im
    #create a blank image from out template
    im = Image.open(input_image)
    #create a drawing object
    draw = ImageDraw.Draw(im)
    #iterate over our list of points and draw corresponding lines
    for i in l:
        draw.line((i['lx'], i['ly'], i['mx'], i['my']), fill=pincolor, width=1)
    #delete our draw object (cleanup and free the memory)
    del draw 
    
    # save image
    #im.save(output_image, "PNG")
    return im
Esempio n. 14
0
    def _generate_thumbnail(self):
        """
        Be aware that this function handle very badly remote backends such as
        s3. You can add in your save() method something like::

            if 's3boto' in settings.DEFAULT_FILE_STORAGE:
                self.external_url = self.image.file.url
        """
        image = None
        if self.external_url:
            import urllib
            filepath, headers = urllib.urlretrieve(self.external_url)
            image = PilImage.open(filepath)
            filename = os.path.basename(filepath)
        elif self.file:
            image = PilImage.open(self.file.path)
            filename = os.path.basename(self.file.name)
        if image is None:
            return
        if image.mode not in ('L', 'RGB'):
            image = image.convert('RGB')
        image.thumbnail(THUMB_SIZE, PilImage.ANTIALIAS)

        destination = StringIO()
        image.save(destination, format='JPEG')
        destination.seek(0)

        self.thumbnail.save(filename, ContentFile(destination.read()))
def mslice( pf, fileout = 'junk.png',field="Density", center="max", width=4) :
	newImage = Image.new("RGB", (1070,2000))
	print fileout 
	p = SlicePlot(pf, "x", field, center=center,width=(width,"pc") )
	p.set_zlim("Density", 1e-23,1e-19)
	p.annotate_velocity(factor=16)
	
	pid = os.getpid()
        p.save("junk{0:06d}".format(pid))

	p = SlicePlot(pf, "y", field, center=center, width=(4,"pc") )
	p.set_zlim("Density", 1e-23,1e-19)
	p.annotate_velocity(factor=16)
        p.save("junk{0:06d}".format(pid))

	file1 = "junk{0:06d}_Slice_x_{1}.png".format(pid,field)
	file2 = "junk{0:06d}_Slice_y_{1}.png".format(pid,field)
	image1 = Image.open(file1)
	image2 = Image.open(file2)

	newImage.paste( image1, (0,0))
	newImage.paste( image2, (0,1000))
	newImage.save(fileout)

	os.remove(file1)
	os.remove(file2)
Esempio n. 16
0
def AlphaOverlay(baseFile, inFile, position, outname=None, format="PNG"):
    """ Overlay an image with an alpha value onto a background image

    Params:
        baseFile --
        inFile --
        position --
        outname=None --
        format="PNG" --

    Returns:
         None
    """
    try:
        bottom = Image.open(baseFile)
        top = Image.open(inFile)
        top.load()  # Sometimes PIL is lazy and forgets to load the image, so we do it explicitly
        r, g, b, a = top.split()
        top = Image.merge("RGB", (r, g, b))
        mask = Image.merge("L", (a,))
        bottom.paste(top, position, mask)
        bottom.save(outname, format)
    except IOError:
        print "cannot Overlay %s onto %s" % (inFile, baseFile)
        return None
		def convertToPNG(imageData):
			inbuff = StringIO.StringIO(imageData)
			outbuff = StringIO.StringIO()
			Image.open(inbuff).save(outbuff, "PNG")
			outbuff.seek(0)
			imageData = outbuff.read()
			return imageData
Esempio n. 18
0
def run():
    pic = Image.open("tests/data/colored_square.jpg").resize((128,128)).convert("RGBA")
    pig = Image.open("tests/data/gray_square.gif").resize((128,128)).convert("L")
    #color_test(np.asarray(pic).reshape(128**2*4,1))
    #gray_test( np.asarray(pig).reshape(128**2  ,1))

    pig = Image.open("tests/data/gray_square.gif").resize((640,480)).convert("L")
Esempio n. 19
0
def open(url):
    """
    """
    bytes = StringIO(urlopen(url).read())
    image = Image.open(bytes)
    
    try:
        image.load()
    except IOError:
        pass
    else:
        return image

    s, h, path, p, q, f = urlparse(url)
    head, tail = splitext(path)
    
    handle, input_filename = mkstemp(prefix='imagemath-', suffix=tail)
    write(handle, bytes.getvalue())
    close(handle)
    
    handle, output_filename = mkstemp(prefix='imagemath-', suffix='.jpg')
    close(handle)
    
    try:
        convert = Popen(('convert', input_filename, output_filename))
        convert.wait()
        
        if convert.returncode != 0:
            raise IOError("Couldn't read %(url)s even with convert" % locals())
        
        return Image.open(output_filename)
    
    finally:
        unlink(input_filename)
        unlink(output_filename)
Esempio n. 20
0
def __diff(img1, img2):
    _img1, _img2 = Image.open(img1), Image.open(img2)
    __img1, __img2 = _img1.load(), _img2.load()
    wdiff, hdiff, wans, hans, wsame, hsame = {}, {}, 0, 0, 0, 0

    for w in range(-3, 8):
        wdiff[w] = 0
        for h in range(-10, 10):
            hdiff[h] = 0
            for x in range(_img1.size[0]):
                for y in range(_img1.size[1]):
                    try:
                        if __img1[x, y] == __img2[x+w, y+h]:
                            wdiff[w] = wdiff[w] + 1
                            hdiff[h] = hdiff[h] + 1
                    except IndexError:
                        pass

    for k, v in wdiff.items():
        if v > wsame:
            wans, wsame  = k, v
    for k, v in hdiff.items():
        if v > hsame:
            hans, hsame  = k, v

    print(wans, hans)
    return (wans, hans)
Esempio n. 21
0
def printOutputs(outputs):
	
	#initialize
	canvas = Image.new("RGB", (330,3350), (255,255,255))
	step = 80
	row = 1
	font = ImageFont.truetype("Arial.ttf",10)
	draw = ImageDraw.Draw(canvas)
	
	#print header
	headerFont = ImageFont.truetype("Arial.ttf",15)
	draw.text((20,30),"Image",font=headerFont, fill=(0,0,0))
	draw.text((120,30),"Best Match",font=headerFont, fill=(0,0,0))
	draw.text((220,30),"Worst Match",font=headerFont, fill=(0,0,0))
	
	#print images
	for output in outputs:
		imageNum = output[0]
		bestImageNum = output[1]
		worstImageNum = output[2]
		image = Image.open(helper_functions.image_path(imageNum))
		bestImage = Image.open(helper_functions.image_path(bestImageNum))
		worstImage = Image.open(helper_functions.image_path(worstImageNum))
		canvas.paste(image,(10,row*step,99,row*step+60))
		canvas.paste(bestImage,(110,row*step,199,row*step+60))
		canvas.paste(worstImage,(210,row*step,299,row*step+60))
		draw.text((20,row*step+63),"Image: " + str(imageNum),font=font, fill=(0,0,0))
		draw.text((120,row*step+63),"Image: " + str(bestImageNum),font=font, fill=(0,0,0))
		draw.text((220,row*step+63),"Image: " + str(worstImageNum),font=font, fill=(0,0,0))
		row += 1
	canvas.save("Part3Output.jpg", "JPEG")
Esempio n. 22
0
def imagen():
    img = Image.open("prueba.png")
    img2= Image.open("prueba.png")
    img6 =Image.open("prueba.png")
    ancho,alto = img.size
    img = eg(img,ancho,alto,img2)
    return img, ancho, alto
Esempio n. 23
0
def draw_matches(matches, qimg, dbimg, outimg):

    print 'Drawing homography verified sift matches...'

    def scaledown(image, max_height):
        scale = 1.0
        hs = float(image.size[1]) / max_height
        if hs > 1:
            w,h = image.size[0]/hs, image.size[1]/hs
            scale /= hs
            image = image.resize((int(w), int(h)), Image.ANTIALIAS)
        return image, scale

    assert os.path.exists(dbimg)
    assert os.path.exists(qimg)
    a = Image.open(qimg)
    b = Image.open(dbimg)
    if a.mode != 'RGB':
        a = a.convert('RGB')
    if b.mode != 'RGB':
        b = b.convert('RGB')
    height = b.size[1]
    a, scale = scaledown(a, height)
    assert a.mode == 'RGB'
    off = a.size[0]
    target = Image.new('RGBA', (a.size[0] + b.size[0], height))

    def xdrawline((start,stop), color='hsl(20,100%,50%)', off=0):
Esempio n. 24
0
def draw_dbimage(C, Q, matchedimg, match):

    print 'Drawing query and database images side by side...'

    qname = Q.name
    dbimg = os.path.join(C.hiresdir,matchedimg+'.jpg')
    qimg = os.path.join(C.querydir,'hires',qname+'.jpg')
    outimg = os.path.join(C.pose_param['resultsdir'],qname+';'+str(match)+';'+matchedimg+'.jpg')

    def scaledown(image, max_height):
        scale = 1.0
        hs = float(image.size[1]) / max_height
        if hs > 1:
            w,h = image.size[0]/hs, image.size[1]/hs
            scale /= hs
            image = image.resize((int(w), int(h)), Image.ANTIALIAS)
        return image, scale

    assert os.path.exists(dbimg)
    assert os.path.exists(qimg)
    a = Image.open(qimg)
    b = Image.open(dbimg)
    if a.mode != 'RGB':
        a = a.convert('RGB')
    if b.mode != 'RGB':
        b = b.convert('RGB')
    height = b.size[1]
    a, scale = scaledown(a, height)
    assert a.mode == 'RGB'
    off = a.size[0]
    target = Image.new('RGBA', (a.size[0] + b.size[0], height))

    def xdrawline((start,stop), color='hsl(20,100%,50%)', off=0):
Esempio n. 25
0
File: image.py Progetto: LCROBOT/rce
 def decode(self, _, imgObj):
     """ Convert a image stored (PIL library readable image file format)
         in a StringIO object to a ROS compatible message
         (sensor_msgs.Image).
     """
     if not _checkIsStringIO(imgObj):
         raise TypeError('Given object is not a StringIO instance.')
     
     # Checking of image according to django.forms.fields.ImageField
     try:
         imgObj.seek(0)
         img = Image.open(imgObj)
         img.verify()
     except:
         raise ValueError('Content of given image could not be verified.')
     
     imgObj.seek(0)
     img = Image.open(imgObj)
     img.load()
     
     # Everything ok, convert PIL.Image to ROS and return it
     if img.mode == 'P':
         img = img.convert('RGB')
     
     rosimage = sensor_msgs.msg.Image()
     rosimage.encoding = ImageConverter._ENCODINGMAP_PY_TO_ROS[img.mode]
     (rosimage.width, rosimage.height) = img.size
     rosimage.step = (ImageConverter._PIL_MODE_CHANNELS[img.mode]
                      * rosimage.width)
     rosimage.data = img.tostring()
     return rosimage
Esempio n. 26
0
    def imagepost(self,**kw):
        registry = RegistryManager.get(request.session.db)
        obj = registry.get("rhwl.easy.genes")
        with registry.cursor() as cr:
            if kw.get("id",0) and int(kw.get("id",0))>0:
                id = [int(kw.get("id",0))]
            else:
                id = obj.search(cr,request.uid,[("name","=",kw.get("no"))])
                if not id:
                    return "NO_DATA_FOUND"
            file_like = cStringIO.StringIO(kw.get("img1").split(";")[-1].split(",")[-1].decode('base64','strict'))
            img = Image.open(file_like)
            width,height = img.size
            file_like2 = cStringIO.StringIO(kw.get("img2").split(";")[-1].split(",")[-1].decode('base64','strict'))
            img2 = Image.open(file_like2)

            region = img2.crop((0,0,width/2,height))
            img.paste(region, (width/2, 0,width,height))
            val={"img":base64.encodestring(img.tostring("jpeg",img.mode))}
            if kw.get("etx",""):
                val["except_note"]=kw.get("etx")

            obj.write(cr,request.uid,id,val,context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")})
            if val.has_key("except_note") or kw.get("is_confirm")=="true":
                o=obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})
                if o.state=="draft":
                    if val.has_key("except_note"):
                        obj.action_state_except(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})
                    elif kw.get("is_confirm")=="true":
                        obj.action_state_confirm(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"})


            return "OK"
Esempio n. 27
0
def draw_tags(C, Q, matches, pose, dname, dlat, dlon, Kd, Kq):


    print 'Drawing homography and tags...'

    qname = Q.name
    dbimg = os.path.join(C.hiresdir,dname+'.jpg')
    qimg = os.path.join(C.querydir,'hires',qname+'.jpg')
    outimg = os.path.join(C.pose_param['resultsdir'],'tags;'+qname+';'+dname+'.jpg')
    H = matches['estH']

    def scaledown(image, max_height):
        scale = 1.0
        hs = float(image.size[1]) / max_height
        if hs > 1:
            w,h = image.size[0]/hs, image.size[1]/hs
            scale /= hs
            image = image.resize((int(w), int(h)), Image.ANTIALIAS)
        return image, scale

    assert os.path.exists(dbimg)
    assert os.path.exists(qimg)
    a = Image.open(qimg)
    b = Image.open(dbimg)
    if a.mode != 'RGB':
        a = a.convert('RGB')
    if b.mode != 'RGB':
        b = b.convert('RGB')
    height = b.size[1]
    a, scale = scaledown(a, height)
    assert a.mode == 'RGB'
    off = a.size[0]
    target = Image.new('RGBA', (a.size[0] + b.size[0], height))

    def xdrawline((start,stop), color='hsl(20,100%,50%)', off=0, width=1):
Esempio n. 28
0
 def thumb(m):
     d = m.groupdict()
     url = d['url']
     old_th = d['th']
     code_origin = m.group()
     code_normal = '[url={0}][img]{1}[/img][/url]'
     tname = 't' + hashurl(url) + '.jpg'
     th = rehost_m.cache_search(tname)
     if th is not None:
         print('.  {0} - from cache'.format(th))
         return code_normal.format(url, th)
     try:
         i = Image.open(open_thing(url)[0])
         if old_th != url:
             t = Image.open(open_thing(old_th)[0])
             f1 = float(i.size[1]) / i.size[0]
             f2 = float(t.size[1]) / t.size[0]
             if abs(f1 - f2) / (f1 + f2) < 0.02 and t.size[0] >= 180:
                 print('.  {0} - good'.format(old_th))
                 rehost_m.cache_write(tname, old_th)
                 return code_origin
         i.thumbnail(THUMB_SIZE, Image.ANTIALIAS)
         i.save(tname, quality=85)
     except IOError as ex:
         print(ex)
         return code_origin
     th = rehost(tname, force_cache=True)
     try:
         os.unlink(tname)
     except:
         pass
     print('.  {0} - new'.format(th))
     return code_normal.format(url, th)
Esempio n. 29
0
def imagecompare(imgfile1, imgfile2):
    try:
        import ImageChops, Image
    except ImportError:
        raise Exception('Python-Imaging package not installed')
    try:
        diffcount = 0.0
        im1 = Image.open(imgfile1)
        im2 = Image.open(imgfile2)

        imgcompdiff = ImageChops.difference(im1, im2)
        diffboundrect = imgcompdiff.getbbox()
        imgdiffcrop = imgcompdiff.crop(diffboundrect)

        data = imgdiffcrop.getdata()

        seq = []
        for row in data:
            seq += list(row)

        for i in xrange(0, imgdiffcrop.size[0] * imgdiffcrop.size[1] * 3, 3):
            if seq[i] != 0 or seq[i+1] != 0 or seq[i+2] != 0:
                diffcount = diffcount + 1.0
        
        diffImgLen = imgcompdiff.size[0] * imgcompdiff.size[1] * 1.0
        diffpercent = (diffcount * 100) / diffImgLen
        return diffpercent
    except IOError:
        raise Exception('Input file does not exist')
Esempio n. 30
0
    def add_new_plymouth(self, customBG, plymouthName):
        # if plymouthName exist return false
        existingPlymouth = self.get_existing_plymouth_list()
        customBG = customBG.encode('utf-8')
        plymouthName = plymouthName.encode('utf-8')
        plymouthName
        if(plymouthName in existingPlymouth):
            return False
        else:
            existingDir = '/var/lib/youker-assistant-daemon/plymouth/existing/'
            customScript = '/var/lib/youker-assistant-daemon/plymouth/defaults/only_background.script'
            defaultplymouthfile = '/var/lib/youker-assistant-daemon/plymouth/defaults/default.plymouth'
			
            # add new plymouth conf dir
            os.mkdir(existingDir + plymouthName)
            shutil.copy(defaultplymouthfile, existingDir + plymouthName + '/default.plymouth')
            # modify config file
            fileHandle = open(existingDir + plymouthName + '/default.plymouth', 'a')
            fileHandle.write('ImageDir=/lib/plymouth/themes/' + plymouthName + '\n')
            fileHandle.write('ScriptFile=/lib/plymouth/themes/' + plymouthName + '/youker.script')
            fileHandle.close()

            # add new system plymouth dir
            os.mkdir('/lib/plymouth/themes/' + plymouthName)
            shutil.copy(customScript, '/lib/plymouth/themes/' + plymouthName + '/youker.script')
            #shutil.copy(customBG, '/lib/plymouth/themes/' + plymouthName + '/customBG.png')
            Image.open(customBG).save('/lib/plymouth/themes/' + plymouthName + '/customBG.png')
			
            return True
Esempio n. 31
0
def red_eye():
    global panelA,panelB
    path = tkFileDialog.askopenfilename()

    print("RED EYE")
    if(len(path)>0):
        cap = cv2.imread(path)
        pic = Image.open(path)
        pic1= Image.open(path)
        width,height=pic.size
        PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor(PREDICTOR_PATH)

        rects = detector(cap)

        for m in range(len(rects)):
        	counter=0
            l_l=width
            l_r=0
            l_t=0
            l_b=height

            r_l=width
            r_r=0	
            r_t=0
            r_b=height
            for i in  predictor(cap, rects[m]).parts() :
                counter=counter+1
                if((counter>36)and(counter<43)):
                    if(l_l>i.x):
                        l_l=i.x
                    if(l_r<i.x):
                        l_r=i.x
                    if(l_t<i.y):
                        l_t=i.y
                    if(l_b>i.y):
                        l_b=i.y
		
                elif((counter>42)and(counter<49)):
                    if(r_l>i.x):
                        r_l=i.x
                    if(r_r<i.x):
                        r_r=i.x     
                    if(r_t<i.y):
                        r_t=i.y
                    if(r_b>i.y):
                        r_b=i.y
        
            for x in range(l_l, l_r):
                for y in range(l_b, l_t):
                    if((len(pic.getpixel((x,y))))==3):
                        r,g,b = pic.getpixel( (x,y) )
                        if((r>1.5*g)and(r>1.5*b)):
                            if(g<b):
                                r=g
                            else:
                                r=b
                        pic.putpixel((x,y),(r,g,b))
               	    else:
                        r,g,b,a = pic.getpixel( (x,y) )
                        if((r>1.5*g)and(r>1.5*b)):
                            if(g<b):
                                r=g
                            else:
                                r=b
                        pic.putpixel((x,y),(r,g,b,a))


            for x in range(r_l, r_r):
                for y in range(r_b, r_t):
                    if((len(pic.getpixel((x,y))))==3):
                        r,g,b = pic.getpixel( (x,y) )
                        if((r>1.5*g)and(r>1.5*b)):
                            if(g<b):
                                r=g
                            else:
                                r=b
                        pic.putpixel((x,y),(r,g,b))
               	    else:
               	        r,g,b,a = pic.getpixel( (x,y) )
                        if(( r>1.5*g)and(r>1.5*b)):
                            if(g<b):
                                r=g
                            else:
                                r=b
                        pic.putpixel((x,y),(r,g,b,a))  


            print('sagar')

        image = ImageTk.PhotoImage(pic1)
        edged = ImageTk.PhotoImage(pic)

		
        if panelA is None or panelB is None:
			# the first panel will store our original image
            panelA = Label(image=image)
            panelA.image = image
            panelA.pack(side="left", padx=10, pady=10)
 
			# while the second panel will store the edge map
            panelB = Label(image=edged)
            panelB.image = edged
            panelB.pack(side="right", padx=10, pady=10)
 
		# otherwise, update the image panels
        else:
			# update the pannels
            panelA.configure(image=image)
            panelB.configure(image=edged)
            panelA.image = image
            panelB.image = edged
Esempio n. 32
0
def convert_png_to_jpeg(image_path):
    im = Image.open(image_path)
    iname = image_path[0:(len(image_path) - 3)] + "jpg"
    im.save(iname, "JPEG")
    os.remove(image_path)
    return iname
# takes threshold file as "canonical" list of experiments and
# files
#
storedProbs = {}
#for thisStack in breakIntoStacks(threshDicts):
#    for threshes in thisStack:
for thisCndSet in breakByConditions(threshDicts):
    stackArray = np.empty((0, 3), dtype=np.uint8)
    print tuple(thisCndSet[0][k] for k in cndKeys), "...",
    for threshes in thisCndSet:
        # print threshes["Slice"],

        # get file->image and thresholds together and apply them

        exampleFilename = fileNameFormat[threshes["Organelle"]] % threshes
        currentImage = Image.open(imageDataPath + exampleFilename)
        asArray = fromimage(currentImage).reshape((numImagePoints, 3))

        # port to thresholdNDArray
        if applyExpertThresholds:
            expertThresholds = dict(((c, threshes[c]) for c in colorNames))
            thresholdNDArray(asArray, expertThresholds)

        # asArray = fromimage(currentImage).reshape((numImagePoints, 3))
        stackArray = np.concatenate((stackArray, asArray))

    org = simplifyOrgStain(threshes["Organelle"], threshes["Stain"])
    # r = threshes["Series"] - 1
    t = timeToIdx(threshes["Time"])

    print org, t
Esempio n. 34
0
    def match(self, patname, srcname):
        """
        given a pattern image and a source image, return the match result and
        the scaling factor  
        """

        p = Image.open(patname).convert('L')
        pa = numpy.array(p)
        pa *= 255.0 / pa.max()

        s = Image.open(srcname).convert('L')
        sa = numpy.array(s)
        sa *= 255.0 / sa.max()

        pre = process.process()
        ex = findextrema.findextrema()
        des = descriptor.descriptor()
        scale = factor.factor()

        pdata = pre.creatdog(pa)
        sdata = pre.creatdog(sa)

        pDes = []
        sDes = []

        # dict to store all the feature matching result
        result = {}

        pFeatures = ex.get_Patextremes(pdata, pa)
        sFeatures = ex.get_Srcextremes(sdata, sa)

        # assign decriptors for each feature points
        pDes = des.creatDes(pFeatures, pa)
        sDes = des.creatDes(sFeatures, sa)

        tree = []

        if sDes == {} or pDes == {}:
            return False
        else:
            # use cKD tree struture to compute the two similar pixels
            tree = scipy.spatial.cKDTree(sDes.values())
            slocList = sDes.keys()
            pDict = {}
            sDict = {}
            for p in pDes.keys():
                x = pDes[p]
                re = tree.query(x,
                                k=2,
                                eps=self.distanceThresh,
                                p=2,
                                distance_upper_bound=numpy.inf)

                if re[0][1] != 0 and re[0][0] / re[0][
                        1] < self.similarityThresh:
                    pLoc = p
                    sLoc = slocList[re[1][0]]
                    distance = re[0][0]

                    # did not been compared before
                    if sDict.has_key(sLoc) == False:

                        # add the result and compared pattern pixel
                        # and source pixel
                        result[(pLoc, sLoc)] = distance
                        pDict[pLoc] = sLoc
                        sDict[sLoc] = pLoc

                    elif distance < result.get((sDict[sLoc], sLoc)):

                        # updates the result and compared pattern pixel
                        # and source pixel
                        del result[(sDict[sLoc], sLoc)]
                        result[(pLoc, sLoc)] = distance
                        del pDict[sDict[sLoc]]
                        pDict[pLoc] = sLoc
                        sDict[sLoc] = pLoc

                elif re[0][1] == 0:
                    pLoc = p
                    sLoc = slocList[re[1][0]]
                    distance = re[0][0]

                    # did not been compared before
                    if sDict.has_key(sLoc) == False:

                        # add the result and compared pattern pixel
                        # and source pixel
                        result[(pLoc, sLoc)] = distance
                        pDict[pLoc] = sLoc
                        sDict[sLoc] = pLoc

                    elif distance < result.get((sDict[sLoc], sLoc)):

                        # updates the result and compared pattern pixel
                        # and source pixel
                        del result[(sDict[sLoc], sLoc)]
                        result[(pLoc, sLoc)] = distance
                        del pDict[sDict[sLoc]]
                        pDict[pLoc] = sLoc
                        sDict[sLoc] = pLoc

        # the list of matched pixels, sorted by the distance
        finResult = sorted(result.items(), reverse=False, key=lambda d: d[1])

        match1 = finResult[0][0]
        match2 = finResult[1][0]
        match3 = finResult[2][0]

        scalingFactor = scale.cal_factor(match1, match2, match3)

        return finResult, scalingFactor
import sys
import os
import Image
import myconfig
import Camera

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "usage: python %s output_folder input_file" % sys.argv[0]
        sys.exit(0)

    output_folder, input_file = sys.argv[1], sys.argv[2]

    offsets = [[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1], [0, 2], [1, 2],
               [2, 2]]

    input_image = Image.open(input_file)
    print 'Input image size: %dx%d' % (input_image.size[0],
                                       input_image.size[1])

    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    camera = Camera.Camera(myconfig.config['psf'])
    downscale = 1.0 / myconfig.config['scale']

    for (x, y) in offsets:
        low_res_file = '%s/S_%d_%d.tif' % (output_folder, x, y)
        camera.take_a_photo(input_image, (x, y), downscale).save(low_res_file)
        print 'Saved output image: %s' % low_res_file
Esempio n. 36
0
    def draw(self, show=True, filename=None, update=False, usecoords=False):
        """Create a 2D depiction of the molecule.

        Optional parameters:
          show -- display on screen (default is True)
          filename -- write to file (default is None)
          update -- update the coordinates of the atoms to those
                    determined by the structure diagram generator
                    (default is False)
          usecoords -- don't calculate 2D coordinates, just use
                       the current coordinates (default is False)

        Tkinter and Python Imaging Library are required for image display.
        """
        obconversion = ob.OBConversion()
        formatok = obconversion.SetOutFormat("_png2")
        if not formatok:
            raise ImportError("PNG depiction support not found. You should "
                              "compile Open Babel with support for Cairo. See "
                              "installation instructions for more "
                              "information.")

        # Need to copy to avoid removing hydrogens from self
        workingmol = Molecule(ob.OBMol(self.OBMol))
        workingmol.removeh()

        if not usecoords:
            _operations['gen2D'].Do(workingmol.OBMol)
        if update:
            if workingmol.OBMol.NumAtoms() != self.OBMol.NumAtoms():
                raise RuntimeError("It is not possible to update the original "
                                   "molecule with the calculated coordinates, "
                                   "as the original molecule contains "
                                   "explicit hydrogens for which no "
                                   "coordinates have been calculated.")
            else:
                for i in range(workingmol.OBMol.NumAtoms()):
                    self.OBMol.GetAtom(i + 1).SetVector(
                        workingmol.OBMol.GetAtom(i + 1).GetVector())
        if filename:
            filedes = None
        else:
            if sys.platform[:3] == "cli" and show:
                raise RuntimeError("It is only possible to show the molecule "
                                   "if you provide a filename. The reason for "
                                   "this is that I kept having problems "
                                   "when using temporary files.")

            filedes, filename = tempfile.mkstemp()

        workingmol.write("_png2", filename=filename, overwrite=True)

        if show:
            if sys.platform[:4] == "java":
                image = javax.imageio.ImageIO.read(java.io.File(filename))
                frame = javax.swing.JFrame(visible=1)
                frame.getContentPane().add(
                    javax.swing.JLabel(javax.swing.ImageIcon(image)))
                frame.setSize(300, 300)
                frame.setDefaultCloseOperation(
                    javax.swing.WindowConstants.DISPOSE_ON_CLOSE)
                frame.show()
            elif sys.platform[:3] == "cli":
                form = _MyForm()
                form.setup(filename, self.title)
                Application.Run(form)
            else:
                if not tk:
                    raise ImportError("Tkinter or Python Imaging Library not "
                                      "found, but is required for image "
                                      "display. See installation instructions "
                                      "for more information.")
                root = tk.Tk()
                root.title((hasattr(self, "title") and self.title)
                           or self.__str__().rstrip())
                frame = tk.Frame(root, colormap="new",
                                 visual='truecolor').pack()
                image = PIL.open(filename)
                imagedata = piltk.PhotoImage(image)
                tk.Label(frame, image=imagedata).pack()
                tk.Button(root, text="Close",
                          command=root.destroy).pack(fill=tk.X)
                root.mainloop()
        if filedes:
            os.close(filedes)
            os.remove(filename)
    print "Directory " + DIRECTORY_DESTINATION + " cannot be found"
    exit()

if DIRECTORY_SOURCE == DIRECTORY_DESTINATION:
    print "Source and destination directory are the same"
    exit()

print "Checking watermark..."

if not os.path.isfile(WATERMARK_PATH):
    print "The watermark " + WATERMARK_PATH + " is not a file"
    exit()

print "Loading watermark..."

IMAGE_WATERMARK_ORIGINAL = Image.open(WATERMARK_PATH)
IMAGE_WATERMARK_ORIGINAL.load()

IMAGE_WATERMARK = IMAGE_WATERMARK_ORIGINAL

PHOTO_NAME = sys.argv[2]

PHOTO_PATH = DIRECTORY_SOURCE + "/" + PHOTO_NAME
if not os.path.isfile(PHOTO_PATH):
    print "The original file " + PHOTO_NAME + " is not a file"
    exit()

print PHOTO_NAME + ": Loading file..."
IMAGE_PHOTO = Image.open(PHOTO_PATH)
IMAGE_PHOTO.load()
Esempio n. 38
0
def convertir(imagen_origen, imagen_destino, lado):
    im = Image.open(imagen_origen)
    im.thumbnail((lado, lado), Image.ANTIALIAS)
    im.save(imagen_destino)
Esempio n. 39
0
 
HTTP=httplib.HTTPSConnection("ringzer0team.com")
Param=urllib.urlencode({})
Headers={"Cookie":"PHPSESSID=ch779ru3qvb5fdc9jm2cnmt752;"}
HTTP.request("GET","/challenges/17",Param,Headers)
Result=HTTP.getresponse().read()

Buffer1=Result.split("<img src=\"data:image/png;base64,")
Buffer2=Buffer1[1].split("\" />")

d=base64.b64decode(Buffer2[0])
e=open("temp.png","wb")
e.write(d)
e.close()

img=Image.open("temp.png")
pixels=img.load()
(x,y)=img.size
for j in range(0,y,1):
    for i in range(0,x,1):
        rgb=pixels[i,j]
        
        if rgb[0] == 0xff & rgb[1] == 0xff & rgb[2] == 0xff:
            pixels[i,j] = (0, 0, 0)
        else:
            pixels[i,j] = (255, 255, 255)
#img.show()
img.save("temp.bmp")

PIPE=subprocess.PIPE
p=subprocess.Popen("temp.exe", stdin=PIPE, stdout=PIPE)
Esempio n. 40
0
 radius = 0.0
 area = 0
 ySum = 0
 xSum = 0
 yCom = 0
 xCom = 0
 x2Sum = 0
 y2Sum = 0
 xySum = 0
 y2Com = 0
 x2Com = 0
 xyCom = 0
 eArray = scipy.zeros((1650, 800), float)
 #im = Image.open("/Users/mdgreenb/Dropbox/In Progress/T82/T82_Stats_%04i.png" % slices)
 im = Image.open(
     "E:\Users\Stardust\Desktop\T152_zSlices2\T152_sliced_%04i.png" %
     slices)
 for x in range(im.size[0] - 1):
     for y in range(im.size[1] - 1):
         val = im.getpixel((x, y))
         if val < 100:
             area = area + 1
             xSum = xSum + x
             ySum = ySum + y
             eArray[x, y] = 1
             x2Sum = x2Sum + (x * x)
             y2Sum = y2Sum + (y * y)
             xySum = xySum + (x * y)
 volume = volume + area
 radius = math.sqrt(area / pi)
 if area > 0:
Esempio n. 41
0
def _lazyloadImage(fp):
    import Image
    fp.seek(0)  #works in almost any case
    return Image.open(fp)
# -*- coding: utf-8 -*-
import time
import glob
import os
import sys
import numpy as np
import matplotlib.pyplot as plt

tifPath = '/mnt/detectors/Pilatus1M/20150128Startup/'  #parameter["tifPath"]
fileRootName = 'align5m'
import Image
import numpy as np

newlist = sorted(glob.glob(tifPath + fileRootName + '_*.tif'))
#print newlist
plt.ion()
for tif in newlist:
    print tif
    im = Image.open(tif)
    imArray = np.array(im)
    plt.imshow(np.log10(imArray))
    plt.draw()
    time.sleep(1)
Esempio n. 43
0
    for line in inFile.readlines():
        if line != '':
            fields = line.rstrip().split(';')
            picPath.append(fields[0])
            picIndex.append(int(fields[1]))

    return (picPath, picIndex)


if __name__ == "__main__":
    [images, indexes] = readFileNames()
if not os.path.exists("modified"):
    os.makedirs("modified")
for img in images:
    image = Image.open(img)
    CropFace(image,
             eye_left=(252, 364),
             eye_right=(420, 366),
             offset_pct=(0.1, 0.1),
             dest_sz=(200,
                      200)).save("modified/" + img.rstrip().split('/')[1] +
                                 "_10_10_200_200.jpg")
    CropFace(image,
             eye_left=(252, 364),
             eye_right=(420, 366),
             offset_pct=(0.2, 0.2),
             dest_sz=(200,
                      200)).save("modified/" + img.rstrip().split('/')[1] +
                                 "_20_20_200_200.jpg")
    CropFace(image,
Esempio n. 44
0
import Image


if len(sys.argv) < 2:
    print ">>>>Error!! Call the script as follows: 'python createRaw.py /<Folder-to-TIFs>/' [ /<DESTINATION-DIR>/ ]"
    exit(1)
src = sys.argv[1]

# List all tif-images from directory
imgs = [name for name in os.listdir(src)
                  if name.lower().endswith('.tif') and not name.startswith('.')]
imgs.sort()
len_str = str(len(imgs))

# Get image sizes
im = Image.open(src+imgs[0])
xx = str(im.size[0])
yy = str(im.size[1])
zz = len_str

# Split to get parent directory and directory base
sample_name = os.path.split(src[:-1])[1]
if not len(sys.argv) == 3:
    parent_dir = os.path.split(src[:-1])[0]
else:
    parent_dir = sys.argv[2]
    parent_dir = parent_dir[:-1]
    
print parent_dir

# (1) convert with Fiji
def process(r):
    output = StringIO.StringIO(r.content)
    img = Image.open(output)
    return entropy(img)
Esempio n. 46
0
if "L" in user_input:
    rot13 = raw_input('Decode or Encode : ')
    if "Encode" in rot13:
        rot13_encode = raw_input('Enter Your String to Encode :')
        ee = codecs.encode(rot13_encode, 'rot_13')
        print " Your Encoded String is : " + ee
    elif "Decode" in rot13:
        rot13_decode = raw_input('Enter Your String to Decode :')
        dd = codecs.encode(rot13_decode, 'rot_13')
        print " Your Decoded String is : " + dd

if "M" in user_input:
    import Image
    if __name__ == '__main__':
        yours = raw_input('Enter Your Image To Invert : ')
        img = Image.open(yours)
        in_pixels = list(img.getdata())
        out_pixels = list()

        for i in range(len(in_pixels)):
            r = in_pixels[i][0]
            g = in_pixels[i][1]
            b = in_pixels[i][2]
            out_pixels.append((255 - r, 255 - g, 255 - b))

        out_img = Image.new(img.mode, img.size)
        out_img.putdata(out_pixels)
        out_img.save("output_inverted.png", "PNG")

if "N" in user_input:
    import re, os
Esempio n. 47
0
def start_photobooth():

    ################################# Begin Step 1 #################################
    show_image(real_path + "/assets/blank.png")
    print "Get Ready"
    GPIO.output(led1_pin, True)
    show_image(real_path + "/assets/instructions.png")
    sleep(prep_delay)
    GPIO.output(led1_pin, False)

    show_image(real_path + "/assets/blank.png")

    camera = picamera.PiCamera()
    pixel_width = 800  #1000 #originally 500: use a smaller size to process faster, and tumblr will only take up to 500 pixels wide for animated gifs
    #pixel_height = monitor_h * pixel_width // monitor_w #optimize for monitor size
    pixel_height = 480  #666
    camera.resolution = (pixel_width, pixel_height)
    camera.vflip = False
    camera.hflip = False
    camera.start_preview()

    #sleep(2) #warm up camera

    ################################# Begin Step 2 #################################
    print "Taking pics"
    now = time.strftime(
        "%Y-%m-%d-%H:%M:%S"
    )  #get the current date and time for the start of the filename
    try:  #take the photos
        #for i, filename in enumerate(camera.capture_continuous(config.file_path + now + '-' + '{counter:02d}.jpg')):
        for i in range(0, total_pics):
            countdown(camera)
            filename = config.file_path + now + '-0' + str(i + 1) + '.jpg'
            camera.capture(filename)
            GPIO.output(led2_pin, True)  #turn on the LED
            print(filename)
            sleep(0.25)  #pause the LED on for just a bit
            GPIO.output(led2_pin, False)  #turn off the LED
            sleep(capture_delay)  # pause in-between shots
            if i == total_pics - 1:
                break
    finally:
        camera.stop_preview()
        camera.close()
    ########################### Begin Step 3 #################################

    print "Creating an animated gif"
    if post_online:
        show_image(real_path + "/assets/uploading.png")
    else:
        show_image(real_path + "/assets/processing.png")
    GPIO.output(led3_pin, True)  #turn on the LED

    #graphicsmagick = "gm convert -size 500x333 -delay " + str(gif_delay) + " " + config.file_path + now + "*.jpg " + config.file_path + now + ".gif"
    #os.system(graphicsmagick) #make the .gif
    im = Image.open(config.file_path + now + "-01.jpg")
    im.save(config.file_path + now + "-01.gif")

    if post_online:  # turn off posting pics online in the variable declarations at the top of this document
        print "Uploading to tumblr. Please check " + config.tumblr_blog + ".tumblr.com soon."
        connected = is_connected(
        )  #check to see if you have an internet connection
        while connected:
            try:
                file_to_upload = config.file_path + now + ".gif"
                client.create_photo(config.tumblr_blog,
                                    state="published",
                                    tags=["photoboothtest", "photobooth"],
                                    data=file_to_upload)
                break
            except ValueError:
                print "Oops. No internect connection. Upload later."
                try:  #make a text file as a note to upload the .gif later
                    file = open(config.file_path + now +
                                "-FILENOTUPLOADED.txt",
                                'w')  # Trying to create a new file or open one
                    file.close()
                except:
                    print('Something went wrong. Could not write file.')
                    sys.exit(0)  # quit Python

    #Make Mosaic
    try:
        create_mosaic(now)
    except Exception, e:
        tb = sys.exc_info()[2]
        traceback.print_exception(e.__class__, e, tb)
Esempio n. 48
0
    def convert(self):
        if not self.convert_list:
            return False
        filelist = self.convert_list[:]
        for filename in filelist:
            self.__setConvertedFlag(filename)
            input_fullname = self.upload_dir + os.path.sep + filename
            video_info = self.__getVideoInfo(input_fullname)
            original_bitrate = video_info["format"]["bit_rate"]
            #话说把浮点型的字符串转为整数型的字符串没有更好的办法吗?
            video_duration = str(int(float(video_info["format"]["duration"])))
            (name, ext) = os.path.splitext(filename)

            #进行转码
            i = 0
            m3u8 = '#EXTM3U\n'
            xml_m3u8 = ''
            xml_text = ''
            output_path = ''
            info = []
            for data in self.output_bitrate:
                if int(data.replace('k', '000')) > int(original_bitrate):
                    continue
                output_path = self.__creatDir(self.output_dir,
                                              name + os.path.sep + str(i + 1))
                output_file = output_path + os.path.sep + name + '.mp4'
                watermark = self.__getWatermark(self.watermark[i])
                cmd_mp4 = self.__getMp4(input_fullname,
                                        self.output_resolution[i], watermark,
                                        data, output_file)
                os.system(cmd_mp4)
                cmd_m3u8 = self.__getM3u8(output_file, 10, output_path)
                os.system(cmd_m3u8)
                m3u8 = m3u8 + '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=' + data.replace(
                    'k',
                    '000') + ',RESOLUTION=' + self.output_resolution[i] + '\n'
                m3u8 = m3u8 + str(i + 1) + '/index.m3u8\n'
                xml_m3u8 = xml_m3u8 + str(i + 1) + '/index.m3u8|'
                xml_text = xml_text + self.text[i] + '|'
                os.remove(output_file)
                info_item = {
                    'path': output_path + "/index.m3u8",
                    'bitrate': data,
                    'resolution': self.output_resolution[i]
                }
                info.append(info_item)
                i = i + 1

            #生成多码率的m3u8文件
            pos = output_path.rfind(os.path.sep)
            self.__createM3u8(m3u8,
                              output_path[:pos] + os.path.sep + 'index.m3u8')

            #生成视频截图
            for i in range(0, self.pic_count):
                pic_output_path = self.__creatDir(self.pic_dir, name)
                start_time = int(video_duration) / self.pic_count * i
                pic_filename = pic_output_path + os.path.sep + str(i +
                                                                   1) + '.jpg'
                video_time = start_time + 3
                if video_time >= int(video_duration):
                    video_time = int(video_duration) - 1
                cmd_pic = self.__getPic(input_fullname, video_time,
                                        pic_filename)
                os.system(cmd_pic)
                im = Image.open(pic_filename)
                im_ss = im.resize(
                    (int(self.pic_resolution[0]), int(self.pic_resolution[1])))
                im_ss.save(pic_filename)

            #生成xml文件
            year = time.strftime("%Y", time.localtime())
            month = time.strftime("%m", time.localtime())
            xml_dir = os.path.sep + year + os.path.sep + month + os.path.sep + name
            xml_url = self.host + self.output_dir[int(self.output_deep
                                                      ):] + xml_dir
            self.__getXML(xml_m3u8[:-1], xml_text[:-1], xml_url,
                          self.output_dir + xml_dir)

            #将转码后的数据存入数据库中
            conn = sqlite3.connect(self.db)
            md5 = self.__getFileMd5(input_fullname)
            sql = "update video set duration=" + video_duration + ", info='" + json.dumps(
                info) + "' where local_md5='" + md5 + "'"
            conn.execute(sql)
            conn.commit()

            #通知API
            if self.API:
                self.__notify(md5)
Esempio n. 49
0
 def image(self, path_img):
     """ Open image file """
     im_open = Image.open(path_img)
     im = im_open.convert("RGB")
     # Convert the RGB image in printable image
     self._convert_image(im)
Esempio n. 50
0
def create_mosaic(jpg_group):
    now = jpg_group
    ##moving original pics to backup
    ##copypics = "cp " + file_path + now + "*.jpg "+ file_path
    ##print copypics
    ##os.system(copypics)

    ##resizing + montaging
    #print "Resizing Pics..." #necessary?
    ##convert -resize 968x648 /home/pi/photobooth/pics/*.jpg /home/pi/photobooth/pics_tmp/*_tmp.jpg
    #graphicsmagick = "gm mogrify -resize 968x648 " + config.file_path + now + "*.jpg"
    #copypics = "cp " + config.file_path + now + "*.jpg "+ config.file_path

    ##print "Resizing with command: " + graphicsmagick
    #os.system(graphicsmagick)
    #os.system(copypics)

    #print "Montaging Pics..."
    #graphicsmagick = "gm montage " + config.file_path + now + "*.jpg -tile 2x2 -geometry 1000x699+10+10 " + config.file_path + now + "_picmontage.jpg"
    #print "Montaging images with command: " + graphicsmagick
    #os.system(graphicsmagick)

    #print "Adding Label..."
    #graphicsmagick = "gm convert -append "+real_path+ "/assets/bn_booth_label_h.jpg  " + config.file_path + now + "_picmontage.jpg " + config.file_path + now + "_print.jpg"
    #print "Adding label with command: " + graphicsmagick
    #os.system(graphicsmagick)

    image = list()
    image.append(Image.open(config.file_path + now + '-01.jpg'))
    image.append(Image.open(config.file_path + now + '-02.jpg'))
    image.append(Image.open(config.file_path + now + '-03.jpg'))
    image.append(Image.open(config.file_path + now + '-04.jpg'))

    x_pic = 500
    y_pic = 375
    x_border = 40
    y_border = 10
    x_total = 1181
    y_total = 1748
    new_pic = Image.new('RGB', (x_total, y_total), (255, 255, 255))
    new_pic.paste(image[0].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_border, y_border))
    new_pic.paste(image[1].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_border, 1 * y_pic + 2 * y_border))
    new_pic.paste(image[2].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_border, 2 * y_pic + 3 * y_border))
    new_pic.paste(image[3].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_border, 3 * y_pic + 4 * y_border))
    new_pic.paste(image[0].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_total - x_border - x_pic, y_border))
    new_pic.paste(image[1].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_total - x_border - x_pic, 1 * y_pic + 2 * y_border))
    new_pic.paste(image[2].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_total - x_border - x_pic, 2 * y_pic + 3 * y_border))
    new_pic.paste(image[3].resize((x_pic, y_pic), Image.ANTIALIAS),
                  (x_total - x_border - x_pic, 3 * y_pic + 4 * y_border))
    new_pic.save(config.file_path + now + '_total.jpg')
    try:
        new_pic.save('/media/PIHARDDRIVE/' + now + '_total.jpg')
    except:
        print "Flash drive not found"
Esempio n. 51
0
#!/usr/bin/python
# convert image files
# usage: python image.py file.ext1 file.ext2
# i.e. python image.py photo.jpg photo.png (where jpg is the original and png is the goal)

import Image
import sys

im = Image.open(str(sys.argv[1]))
im.save(str(sys.argv[2]))
Esempio n. 52
0
"installing" icon animation and turn it into a base image plus a set
of overlays, as needed by the recovery UI code.  Run with the names of
all the input frames on the command line, in order."""

import sys
try:
    import Image
except ImportError:
    print "This script requires the Python Imaging Library to be installed."
    sys.exit(1)

# Find the smallest box that contains all the pixels which change
# between images.

print "reading", sys.argv[1]
base = Image.open(sys.argv[1])

minmini = base.size[0] - 1
maxmaxi = 0
minminj = base.size[1] - 1
maxmaxj = 0

for top_name in sys.argv[2:]:
    print "reading", top_name
    top = Image.open(top_name)

    assert base.size == top.size

    mini = base.size[0] - 1
    maxi = 0
    minj = base.size[1] - 1
Esempio n. 53
0
 def _tile_image(self, data):
     """
     Tile binary content as PIL Image.
     """
     image = Image.open(StringIO(data))
     return image.convert('RGBA')
Esempio n. 54
0
import os
import sys
import Image

if (len(sys.argv) == 1):
    print "Please provide Image folder path as an argument."
    print "Usage: python thumbnail_factory.py <FolderPath>"
    sys.exit()
rootdir = sys.argv[1]

for root, subFolders, files in os.walk(rootdir):
    for filename in files:
        if "_thumbnail" in filename:
            continue
        filepath = os.path.join(root, filename)
        thumbnail_path = str(
            os.path.splitext(filepath)[0]) + "_thumbnail" + str(
                os.path.splitext(filepath)[1])

        out = file(thumbnail_path, "w")
        try:
            img = Image.open(filepath)
            print "Generating Thumbnail for " + filepath
            img.thumbnail((100, 100))
            img.save(out, 'JPEG')
        except Exception as e:
            print "Error for " + filepath + " : " + str(e)
        finally:
            out.close()
Esempio n. 55
0
import Image
import sys

# from http://stackoverflow.com/questions/10640114/overlay-two-same-sized-images-in-python

if len(sys.argv) < 3:
    sys.exit("Use: python blendpic.py 1.png 2.png")

background = Image.open(sys.argv[1])
overlay = Image.open(sys.argv[2])

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

new_img = Image.blend(background, overlay, 0.5)
new_img.save("blend.png", "PNG")
import Image, ImageFilter
im = Image.open('C:\Users\Administrator\Desktop\IMG_5076 (1).JPG')
im2 = im.filter(ImageFilter.BLUR)
im2.save('C:\Users\Administrator\Desktop\IMG_5076 (1)blur.JPG', 'jpeg')
Esempio n. 57
0
import Image
import os
import glob

mergedImg = Image.new("RGBA", (200 * (len(glob.glob("*.jpg")) + 1), 80),
                      (0, 0, 0, 0))
count = 0
for files in glob.glob("*.jpg"):
    count = count + 1
    img = Image.open(files)
    size = img.size
    ratio = float(size[1]) / 80
    size = int(round(float(size[0]) / ratio, 0)), 80
    img.thumbnail(size, Image.ANTIALIAS)
    w = 200 * count - size[0] / 2
    mergedImg.paste(img, (w, 0))
    print files + ': ', 200 * count - 40

mergedImg.save('image.jpg', quality=90)
Esempio n. 58
0
def load_default():
    "Load a default font."
    from StringIO import StringIO
    import base64
    f = ImageFont()
    f._load_pilfont_data(
        # courB08
        StringIO(
            base64.decodestring('''
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA
BgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL
AAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA
AAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB
ACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A
BAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB
//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA
AAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH
AAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA
ZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv
AAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/
/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5
AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA
AP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG
AAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA
BgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA
AMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA
2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF
AAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////
+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA
////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA
BgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv
AAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA
AAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA
AUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA
BQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//
//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA
AP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF
AAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB
mwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn
AAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA
AAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7
AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA
Av/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB
//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA
AAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ
AAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC
DgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ
AAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/
+wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5
AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/
///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG
AAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA
BQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA
Am0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC
eQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG
AAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////
+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA
////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA
BgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT
AAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A
AALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA
Au4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA
Bf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//
//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA
AP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ
AAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA
LQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5
AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA
AABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5
AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA
AP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG
AAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA
EgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK
AJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA
pQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG
AAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////
+QAGAAIAzgAKANUAEw==
''')),
        Image.open(
            StringIO(
                base64.decodestring('''
iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u
Mc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9
M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g
LeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F
IUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA
Bu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791
NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx
in0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9
SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY
AYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt
y8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG
ABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY
lODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H
/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3
AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47
c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/
/yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw
pEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv
oJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR
evta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA
AAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//
Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR
w7IkEbzhVQAAAABJRU5ErkJggg==
'''))))
    return f
Esempio n. 59
0
def test():
    "Test Hough transform with pentagon."
    im = Image.open("pentagon.png").convert("L")
    him = hough(im)
    him.save("ho5.bmp")
Esempio n. 60
0
	tif_file = ocr_tmp + 'code_' + suffix + '.tif'
	txt_name = ocr_tmp + 'code_' + suffix
	txt_file = txt_name + '.txt'
	try:
		opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
		u=opener.open(url_code)
		content =  u.read()
		f = open(jfif_file, 'w')
		f.write(content)
		f.close()
	except Exception, e:
		print e
		if os.path.exists(jfif_file):
			os.remove(jfif_file)
		return None
	im = Image.open(jfif_file)
	im = im.convert('L')
	im.save(tif_file)
	os.system(ocr_app + ' ' + tif_file + ' ' + txt_name + ' -l num')
	code_file = open(txt_file, "r")
	code = code_file.read().replace(' ','').replace('\n', '')
	code_file.close()
	if os.path.exists(jfif_file):
		os.remove(jfif_file)
	if os.path.exists(tif_file):
		os.remove(tif_file)
	if os.path.exists(txt_file):
		os.remove(txt_file)
	return code

# Encode and print password