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
Пример #2
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"
Пример #4
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)
Пример #5
0
 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
Пример #6
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 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()
Пример #8
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):
Пример #9
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
Пример #10
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):
Пример #11
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):
Пример #12
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"
Пример #13
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')
Пример #14
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)
Пример #15
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
Пример #16
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")
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
Пример #18
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
Пример #19
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))
Пример #20
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)
Пример #21
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!'
Пример #22
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)
Пример #23
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])
Пример #24
0
		def convertToPNG(imageData):
			inbuff = StringIO.StringIO(imageData)
			outbuff = StringIO.StringIO()
			Image.open(inbuff).save(outbuff, "PNG")
			outbuff.seek(0)
			imageData = outbuff.read()
			return imageData
Пример #25
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))
Пример #26
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")
Пример #27
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
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)
Пример #29
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)
Пример #30
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}