tbabb
tbabb
Recreational Programming in Python
28 posts
Don't wanna be here? Send us removal request.
tbabb · 8 years ago
Text
Got a new Raspberry PI zero w  so I wrote a more pythonic interface for general IO pins. Updated!
I wanted to use wxpython but every time I tried to load it for 3.x I got a memory error. I was able to load wxpython for 2.7 so that's what this is written in. I did it to interface with wx custom events easily.
My solution to both reading and using interrupts is to hijack the interrupt and store every input in an input buffer. That way the user can just set each pins function and read all data that comes in. The problem is that the input buffer grows for the lifetime of the object. 
I made the read pulselist robust with timeouts but I have not figured out conversion to data and vise-versa but never the less this is a working Idea of a pythonic class that I had in mind.
https://pastebin.com/W4yNpYjb
Update for Python 3, now with even less bugs and errors!
https://pastebin.com/Gn48yjP7
example of use,
tom = Pinrack()
tom.pin[7].ifunct = mycallbackfuction
import random data = [random.randint(0,255) for i in range(100)] tom.send_grouped_data(data,[7,],chain = True,baud=80) pulselist = [(int(round(random.uniform(0.,1.))),random.uniform(0.,1.)) for i in range(100)] tom.send_grouped_puses(pulselist,[7,]) print([i.outbuff for i in tom.pin]) print([i.ifunct for i in tom.pin]) tom.close()
Here is something completely different, I used a simple integer to pulse width conversion and pickle to make a object transporter.
tom = Pinrack() testobj = [1,2,3,'a','the'] tom.Transporter_beam_out(testobj,[7,]) t2 = tom.Transporter_beam_in([7,]) print(t2)
(Fails frequently! For redshirt objects only! Needs python uncertainty compensator.)
0 notes
tbabb · 8 years ago
Photo
Tumblr media
The mandel a number based on z - z**n + c using the Number Abstract Base Class in Python.
Here is an Idea that I have had for a while but until the ABC I couldn't get a framework together.
The code; https://pastebin.com/04dFRaDa
The mandel works like this,
All internal calculations are done in Fd so import both numbers from newnumber.
    from newnumber import Fd,mandel
Some definitions are in order. The infinite string of numbers created by  z**n + c  is called a soul line. If Z starts at (0,0,0) the sole line is said to be root. If Z starts off of the root soul line it is called an aura. The soul pointer shows what iteration the number lies on and is meaningless for auras.
The inputs are (C, Z, dimension, soul pointer),
    c = mandel(1,0,0,0)
    for i in range(10):         print(c.Z())        c.increment_sp()
    (0.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (2.0+0.0j+0.0k)
Zero dimensional mandel’s are constants and all aura’s are root.
Operations mandel to mandel are Z to Z , C to C . I wasn't sure how to handle dimensions so +- is lower of the two and */ is higher of the two. Operation result in an aura and the soulp is set to the highest of the two.
    a = mandel(1,1,0,0)
    b = a + c
    print(b)     C : (2.0+0.0j+0.0k)     Z : (3.0+0.0j+0.0k)     Dim : 0     Soulp : 10     Aura : True
Operations mandel to x are C to x, Z to x.
    b = a*5
    print(b)     C : (5.0+0.0j+0.0k)     Z : (5.0+0.0j+0.0k)     Dim : 0     Soulp : 0     Aura : True
One dimensional mandel’s are linear.
    a = mandel(1,0,1,0)
    for i in range(10):
        print(a.Z())         a.increment_sp()
    (0.0+0.0j+0.0k)     (1.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (3.0+0.0j+0.0k)     (4.0+0.0j+0.0k)     (5.0+0.0j+0.0k)     (6.0+0.0j+0.0k)     (7.0+0.0j+0.0k)     (8.0+0.0j+0.0k)     (9.0+0.0j+0.0k)
Two dimensional and beyond are exponential.
    a = mandel(1,0,2,0)
    for i in range(10):         print(a.Z())         a.increment_sp()
    (0.0+0.0j+0.0k)     (1.0+0.0j+0.0k)     (2.0+0.0j+0.0k)     (5.0+0.0j+0.0k)     (26.0+0.0j+0.0k)     (677.0+0.0j+0.0k)     (458330.0+0.0j+0.0k)     (210066391040.0+0.0j+0.0k)     (4.412788594124235e+22+0.0j+0.0k)     (inf+0.0j+0.0k)
Here is one number from the Twins.
    a = mandel(Fd(-.7, 0.1333333333333333,.2),Fd(0,0,0),5,0)
    for i in range(10):         print(a.Z())        a.increment_sp()
    (0.0+0.0j+0.0k)     (-0.699999988079071+0.13333334028720856j+0.20000000298023224k)     (-0.6512947082519531+0.2626233696937561j+0.39393505454063416k)     (-0.3355112373828888+0.16607318818569183j+0.24910977482795715k)     (-0.684900164604187+0.13019981980323792j+0.19529972970485687k)     (-0.65702885389328+0.24914729595184326j+0.3737209439277649k)     (-0.3504582643508911+0.1886182278394699j+0.28292733430862427k)     (-0.6823979616165161+0.12573394179344177j+0.18860089778900146k)     (-0.6684328317642212+0.24513068795204163j+0.36769604682922363k)     (-0.33876651525497437+0.2036655992269516j+0.3054983913898468k)
Power has not been implemented yet.
Here is GLcanvas example of the Twins using the mandel.
https://pastebin.com/5MaR4GP6
As always feel free to take any code you want.
0 notes
tbabb · 8 years ago
Photo
Tumblr media
A fractal memory.
Original file,
https://drive.google.com/file/d/0B-R30L8s0o87NjNwR0s0R2VkN0E/view?usp=sharing
Video file,
https://drive.google.com/open?id=0B-R30L8s0o87Nlo4Mm1CTWRPNnc
Why would anyone want a storage so inefficient is a good question. I am thinking that I can use it somehow in conjunction with Neural Nets. 
I made the Fd in order to produce a richer set of Julia sets for fractal image representation. I than used inspyered to make an evolutionary model to explore the phase space, looking for points that occupied ([-1, 1], [-1, 1], [-1, 1]) the longest.
435 Fd’s
https://drive.google.com/open?id=10FPtdru7QP29Nt_NRdZjKeHVEtorm0KxNiOifDudGKY
I used one of the galaxy looking ones to sample an image after scaling and centering and than wrote the resultant sample back to a bank image many times with different random starting points. Because this fractal had an attractor each list would filter down to the image areas in the same spot and by using scipy interpolation a passable image could be made with minimal information.
I searched the fractal list for different fractals when I came across one that looked like a gem and I thought that this would make a more uniform picture and tried writing the same string with many random starting points. Unlike the spiral fractal Z **5 + [0.6953774277970728, 0.3802862927981292, -0.6549478421629558] , this interpolated image came back looking completely random. That’s when I thought that this could be used as a sort of storage where there is an infinite amount of different choices between .1 and .12 and the imperfections might help in some sort of AI endeavor.
Here is the code,
https://pastebin.com/Ddu6G42Y
You will also need the Fd file referenced as newnumber’
https://pastebin.com/DvPWGuF0
Here is something useful one could do with it, watermarking.
    from fractalmem  import *     watermarkimg= FractalMemmory('water.png’)
    for ci, i in enumerate(someimageurls):
        imgFM =  FractalMemmory(i)
        mem =  watermarkimg.extract_memory(ci/100.)
        if imgFM.add_memory(mem,ci/100.):
            img = imgFM.dump_memory()
            img.save(f’watermaked{i[-8:-4]}.png’)
youtube
0 notes
tbabb · 8 years ago
Photo
Tumblr media
GLcanvis test for WXPython Phoenix using Fd fractals.
Here’s the code.
https://pastebin.com/3mCiSWJv
needs the Fd script,
https://pastebin.com/DvPWGuF0
Here is 435 interesting Fd’s
https://docs.google.com/document/d/10FPtdru7QP29Nt_NRdZjKeHVEtorm0KxNiOifDudGKY/edit?usp=sharing
0 notes
tbabb · 8 years ago
Text
Using abstract base class for writing a number.
I’ve used the abstract base class for complex numbers to write the Funky Dootle number.
Here is the code.
https://pastebin.com/DvPWGuF0
examples,
Fd(5,5,0)*5 Out[2]: (25.0+25.0j+0.0k)
Fd(5,0,0)*5 Out[3]: (25.0+0.0j+0.0k)
Fd(5,0,0)**2 Out[4]: (25.0+0.0j+0.0k)
The twins from below are now something like this,
import random,math,itertools from PIL import Image import Fd
def mandle(a1):    j,c = a1[0],a1[1]    j = j**5 + c    return ([j,c])
def IFS_gen(Fn,Io):    Fn = Fn    Io = Io    Inext = Io    while 1:        yield Inext        Inext = Fn(Inext)
def checkval(Valu2):    if math.isnan(Valu2._real):        Valu2._real = 1.    if math.isnan(Valu2._imag):        Valu2._imag = 1.    if math.isnan(Valu2._funk):        Valu2._funk = 1.    if Valu2._real > 1.:        Valu2._real = 1.    elif Valu2._real < -1.:        Valu2._real = -1.    if Valu2._imag > 1.:        Valu2._imag = 1.    elif Valu2._imag < -1.:        Valu2._imag = -1.    if Valu2._funk > 1.:        Valu2._funk = 1.    elif Valu2._funk < -1.:        Valu2._funk = -1.    return Valu2
superimg = [[0. for i in range(4098)] for j in range(4098)] superimg2 = [[0. for i in range(4098)] for j in range(4098)]
def imgux(gray,fname):        im = Image.new('L',(len(gray[int(len(gray)/2)]),len(gray)))       [[im.putpixel((c,k),int(l)) for k,l in enumerate(i)] for c,i in enumerate(gray)]    im.save(fname)
for FD in (Fd(-.7,0.1333333333333333,.2),Fd(-.7,0.1666666666666667,.2),Fd(-.7,-0.1666666666666667,.2),Fd(-.7,-0.1333333333333333,.2)):    for extraitir in range(60):        rnum = Fd(0,0,0)        rnum = Fd(random.uniform(-1.,1.),random.uniform(-1.,1.),random.uniform(-1.,1.))        newIFS = IFS_gen(mandle,[rnum,FD])               for itercount in range(20000):            nextnum = next(newIFS)            nextnum[0] = checkval(nextnum[0])                      superimg[int(nextnum[0]._imag * 2048.)+ 2047][int(nextnum[0]._real * 2048.)+ 2047]  = 255#int((i+1) * 4.25)            superimg2[int(nextnum[0]._funk * 2048.)+ 2047][int(nextnum[0]._real * 2048.)+ 2047] = 255#int((i+1) * 4.25)            #print(int(nextnum[0]._imag * 2048.)+ 2047,int(nextnum[0]._real * 2048.)+ 2047) imgux(superimg,'c:\\tom2\\twins\\realimag3.png') imgux(superimg2,'c:\\tom2\\twins\\realfunk3.png')
https://pastebin.com/4Gc1i4c9
0 notes
tbabb · 8 years ago
Photo
Tumblr media
The Twins (4 points z*z*z*z + c).
http://pastebin.com/vjyy11eH
a repost from my wu-wu blog.
http://sycamorecanyon.tumblr.com/
0 notes
tbabb · 9 years ago
Photo
Tumblr media Tumblr media Tumblr media Tumblr media
Here is a copy of A Fractal memory class for anyone interested.
http://pastebin.com/R2BGLnH1
some stuff it can do;
" >>> tom = FractalMemmory(None) >>> def bla2(a,b):            return b
>>> tom.add_image('nebula.png',.2,bla2) >>> difference_histogram_RGB_lists = tom.recoghist(’nebula.png') >>> tom.graph_hist(difference_histogram_RGB_lists) >>> mem = tom.extract_memory(.2) >>> tom.add_memory(mem,.1,bla2) >>> difference_histogram_RGB_lists = tom.recoghist('nebula.png') >>> tom.graph_hist(difference_histogram_RGB_lists) >>> image = tom.dump_memory() >>> image.save('memdump.png') >>> image = tom.extract_image([.2]) >>> image.save(’fractalparts.png') " and as an extra bonus I included a bunch of neural net activation functions and linear fractal compression routines.
" >>> Binarystep(.5) 1.0 >>> Softstep(.5) 0.6224593312018546 >>> TanH(.5) 0.4621171572600098 >>> Softsign(.5) 0.3333333333333333 >>> Rectifier(.5) 0.5 >>> ParametericRectifiedLinearUnit(.5,.5) 0.5 >>> ExponentialLinearUnit(.5,.5) 0.5 >>> SoftPlus(.5) 0.9740769841801067 >>> Bentidentity(.5) 0.5590169943749475 >>> SoftExponential(.5,.5) 1.0680508333754828 >>> Gaussian(.5) 0.7788007830714049 >>> Sinc(.5) 0.958851077208406 " keep your layers below .25 or it will go to infinity. The layer list default to 400 but I have successfully done over 1000 with good signal to noise ratio. because memories are just images you can open any image as a memory.
0 notes
tbabb · 9 years ago
Photo
Tumblr media Tumblr media
Fractal decomposition of images using the Collage theorem.
This is a case where it is probably easier to look at the code than to talk about it. PIL is the main workhorse here, I use numpy for no good reason, could easily be made pure python.
"In mathematics, the collage theorem characterises an iterated function system whose attractor is close, relative to the Hausdorff metric, to a given set. The IFS described is composed of contractions whose images, as a collage or union when mapping the given set, are arbitrarily close to the given set. "
I'v selected the quantities used in these pictures to show off the artifacts created and not for the best picture.
The Collage theorem says that if I can take a group of pixels and shrink them and place them next to each them, shrink them againe and so on until you have a patch. if this patch of pixels matches parts of the image it can than be described by the small set and the shrinking formula thru iteration (the IFS). There has to be an infinite number of IFS's for any given image. Collectively I will call this set the fractal phase space. Because infinities are difficult to deal with I'm going to restrict myself to only three IFS formulas, a linear contraction, a diagonal contraction, a rotational contraction.
First imports and helper functions.
    from PIL import Image,ImageChops,ImageStat,ImageOps     import numpy as np
    def imgtouxmRGB(tomimg):                 r,g,b = tomimg.split()         r = r.resize((4098,4098))         g = g.resize((4098,4098))         b = b.resize((4098,4098))         trdataR = r.getdata()         trdataG = g.getdata()         trdataB = b.getdata()         uxmR = np.array(trdataR).reshape(4098, 4098)         uxmG = np.array(trdataG).reshape(4098, 4098)         uxmB = np.array(trdataB).reshape(4098, 4098)         del tomimg         return uxmR,uxmG,uxmB
    def imguxret(gray):         im = Image.fromarray(np.uint8(gray))            return im
Linear Contraction
    def feqencyextractor(testimg,pixelfrequency,imgtype = 1,max_pixel = 255):         nimg2 = Image.new('RGB',testimg.size,(127,127,127))         nimg3 = Image.new('RGB',testimg.size,(0,0,0))         for k in [0,90,180,270]:             img = testimg.rotate(k)             for i in range(20):                 shkimg = img.resize((testimg.size[0]-pixelfrequency,testimg.size[1]))                 shkimg = ImageChops.invert(shkimg)                 tmpimg = img.copy()                 tmpimg.paste(shkimg,(pixelfrequency,0))                 img = ImageChops.blend(img,tmpimg,.5)                    nimg = img.crop((int((pixelfrequency*20)/2),0,testimg.size[0],testimg.size[1]))             nimg = nimg.resize(testimg.size)             nimg = nimg.rotate(360 - k)             img = img.rotate(360 - k)             nimg2 = ImageChops.add_modulo(nimg2,img)             nimg3 = ImageChops.blend(nimg3,nimg,.5)         if imgtype == 1:             return nimg3         elif imgtype == 2:             return nimg2         elif imgtype == 3:             r,g,b = imgtouxmRGB(nimg3)             nr = []             for i in r:                 nnr = []                 for j in i:                                         if j == 127:                         nnr.append(max_pixel)                     else:                         nnr.append(0)                 nr.append(nnr)             ng = []             for i in g:                 nng = []                 for j in i:                     if j == 127:                         nng.append(max_pixel)                     else:                         nng.append(0)                 ng.append(nng)             nb = []             for i in b:                 nnb = []                 for j in i:                     if j == 127:                         nnb.append(max_pixel)                     else:                         nnb.append(0)                 nb.append(nnb)             nr = np.array(nr)             ng = np.array(ng)             nb = np.array(nb)             r2 = imguxret(nr)             g2 = imguxret(ng)             b2 = imguxret(nb)             return r2,g2,b2
Diagonal Contraction
    def feqencyextractor_diag(testimg,pixelfrequency,imgtype = 1,max_pixel = 255):         nimg2 = Image.new('RGB',testimg.size,(127,127,127))         nimg3 = Image.new('RGB',testimg.size,(0,0,0))         for k in [0,90,180,270]:             img = testimg.rotate(k)                     for i in range(20):                 shkimg = img.resize((testimg.size[0]-pixelfrequency,testimg.size[1]-pixelfrequency))                 shkimg = ImageChops.invert(shkimg)                 tmpimg = img.copy()                 tmpimg.paste(shkimg,(pixelfrequency,pixelfrequency))                 img = ImageChops.blend(img,tmpimg,.5)                                img = img.rotate(360 - k)             nimg2 = ImageChops.add_modulo(nimg2,img)             nimg3 = ImageChops.blend(nimg3,img,.5)         if imgtype == 1:             return nimg3
       elif imgtype == 2:
           return nimg2        elif imgtype == 3:            r,g,b = imgtouxmRGB(nimg3)            nr = []            for i in r:                nnr = []                for j in i:                                        if j == 127:                        nnr.append(max_pixel)                    else:                        nnr.append(0)                nr.append(nnr)            ng = []            for i in g:                nng = []                for j in i:                    if j == 127:                        nng.append(max_pixel)                    else:                        nng.append(0)                ng.append(nng)            nb = []            for i in b:                nnb = []                for j in i:                    if j == 127:                        nnb.append(max_pixel)                    else:                        nnb.append(0)                nb.append(nnb)            nr = np.array(nr)            ng = np.array(ng)            nb = np.array(nb)            r2 = imguxret(nr)            g2 = imguxret(ng)            b2 = imguxret(nb)            return r2,g2,b2
Rotational Contraction
    def shrinky_rot(img,step = 2,rotation_deg = 1):         degrees = [0, 180, 120, 90 ,60]         im2 = img.copy()         smaller = img.resize((img.size[0]-(step*2),img.size[1]-(step*2)))         smaller = smaller.rotate(rotation_deg)         smaller = ImageChops.invert(smaller)         im2.paste(smaller,(step,step))         im2 = ImageChops.blend(img,im2,.5)         return im2
    def feqencyextractor_rot(testimg,pixelfrequency,imgtype = 1,max_pixel = 255,rotation = 2):         nimg2 = Image.new('RGB',testimg.size,(127,127,127))         nimg3 = Image.new('RGB',testimg.size,(0,0,0))         for k in [0,90,180,270]:             img = testimg.rotate(k)                   for i in range(20):                 img = shrinky_rot(img,pixelfrequency,rotation)                    img = img.rotate(360 - k)             nimg2 = ImageChops.add_modulo(nimg2,img)             nimg3 = ImageChops.blend(nimg3,img,.5)         if imgtype == 1:
           return nimg3        elif imgtype == 2:            return nimg2        elif imgtype == 3:            r,g,b = imgtouxmRGB(nimg3)            nr = []            for i in r:                nnr = []                for j in i:                                        if j == 127:                        nnr.append(max_pixel)                    else:                        nnr.append(0)                nr.append(nnr)            ng = []            for i in g:                nng = []                for j in i:                    if j == 127:                        nng.append(max_pixel)                    else:                        nng.append(0)                ng.append(nng)            nb = []            for i in b:                nnb = []                for j in i:                    if j == 127:                        nnb.append(max_pixel)                    else:                        nnb.append(0)                nb.append(nnb)            nr = np.array(nr)            ng = np.array(ng)            nb = np.array(nb)            r2 = imguxret(nr)            g2 = imguxret(ng)            b2 = imguxret(nb)            return r2,g2,b2
Next I construct a map of the of pixels that fit the IFS's for various pixel layers making the smallest frequency brightest.
    testimg = Image.open('Atlantis.png’)     testimg = testimg.resize((4098,4098))
    mimgR = Image.new('L',testimg.size)     mimgG = Image.new('L',testimg.size)     mimgB = Image.new('L',testimg.size)     for i in range(2,255,25):         print i,         img = feqencyextractor_diag(testimg,i,3,257-i)         img2 = feqencyextractor(testimg,i,3,257-i)             img3 = feqencyextractor_rot(testimg,i,3,257-i,4)             im3R = ImageChops.lighter(img2[0],img[0])            im3R = ImageChops.lighter(img3[0],im3R)             im3G = ImageChops.lighter(img2[1],img[1])             im3G = ImageChops.lighter(img3[1],im3G)            im3B = ImageChops.lighter(img2[2],img[2])           im3B = ImageChops.lighter(img3[2],im3B)             mimgR = ImageChops.lighter(im3R,mimgR)         mimgG = ImageChops.lighter(im3G,mimgG)         mimgB = ImageChops.lighter(im3B,mimgB)     finimg = Image.merge('RGB',(mimgR,mimgG,mimgB))     finimg.save('Atlantis_Phase_001.png')     finimg = ImageChops.multiply(finimg,testimg)     finimg.save( ‘ Atlantis_Phase_M_001.png')     finimg = ImageChops.blend(finimg,testimg,.5)     finimg.save(' Atlantis_Phase_B_001.png .png')
testimg = finimg
And iretate abought three times.
Pictured above is this phase map. Next the original image is multiplied by the phase map, placing the map into the images phase space.
Tumblr media
 next the map is blended,  with the original image and the whole process repeated. Each iteration than forces the pixel values to adopt the IFS sub-fractal phase space frequency making the image a fractal of itself.
Tumblr media
For anyone that has seen convolutional neural networks we can see that this process is doing the same job of decomposing the image into all the possible combinations of the "features" with fractals much more efficiently.
Here is everything and the reverse contractions , mirror contractions, and a bunch of junk,
http://pastebin.com/CkpbQtFb
as always feel free to take, appropriate, slice, dice and whatever to the code.
Here is a link to my wu-wu blog where I use this algorithm on ancient artifacts,
http://sycamorecanyon.tumblr.com/
1 note · View note
tbabb · 10 years ago
Photo
Tumblr media
I have been messing with double fractal encoding (discussed in earlier posts) and I have been trying a number of different ideas. Here is a one where instead of a scale list composed of forward/reverse and scale it is based on a 8x8 grid to describe the transformation. I was inspired by this video on kinetic sculpture;
https://www.youtube.com/watch?v=D2HF-1xjpP8
Here is the code.
http://pastebin.com/cptUzbUL
As always feel free to chop, splice, slice or appropriate any code you would like.
0 notes
tbabb · 10 years ago
Text
One Dimensional Fractal encoding.
First we start with a data string.
Tumblr media
squash it down,
Tumblr media
Make a copy of the original data string with transformed copy's of the squashed versions. In this case forward/reverse and scale.
Tumblr media
repeat.
Tumblr media
When you feel you have finished you will have decomposed the data into two parts. The shrunk part that I’ll call the dynamic part, and a set of transformations which I will call the static part. I can reconstruct the whole list fairly well by just taking any dynamic seed and running it threw the static transformations and shrink and repeat. It works better if you use the original dynamic seed like a rubber stamp.
Here are some functions for you to play with.
    def colorlistfract(colorlist,slicesize):         shrunklist = [0. for i in range(int(len(colorlist)/slicesize))]         colorlist = [c/255. for c in colorlist]         for j in range(len(colorlist)):
            if shrunklist[int(j/slicesize)-1] == 0.:                 shrunklist[int(j/slicesize)-1] = float(colorlist[j])             else:                 shrunklist[int(j/slicesize)-1] = (shrunklist[int(j/slicesize)-1] +(colorlist[j]))/2.
        coloriter = iter(colorlist)         shrunklistava = float(sum(shrunklist))/float(len(shrunklist))         shrunklistrev = shrunklist[:]         shrunklistrev.reverse()         forrevl2 = []         for k in range(int(slicesize)):             shortcolorlist = []             for l in range(len(shrunklist)):                 try:                     c1 = coloriter.next()                 except StopIteration:                     c1 = shrunklist[l]                 shortcolorlist.append(c1)             fow = sum([abs(a-b) for a,b in zip(shortcolorlist,shrunklist)])             rev = sum([abs(a-b) for a,b in zip(shortcolorlist,shrunklistrev)])             newava = 0.             try:                 newava = (float(sum(shortcolorlist))/float(len(shortcolorlist)))/shrunklistava             except ZeroDivisionError:                 #print 'ZeroDivisionError'                  newava = 1.             if fow <= rev:                 forrevl2.append((0,newava))             else:                forrevl2.append((1,newava))         return ((shrunklist,forrevl2))
def recoverlist(shrunkcolorlist,slicesize):    shrunklist = shrunkcolorlist[0][:]    shrunklistrev = shrunkcolorlist[0][:]    shrunklistrev.reverse()    keylist = shrunkcolorlist[1][:]    newcolorlist = []    for k in keylist:        if k[0] == 0:            newl = [i *k[1]+.01 for i in shrunklist]            newcolorlist.extend(newl)        elif k[0] == 1:            newl = [i *k[1]+.01 for i in shrunklistrev]            newcolorlist.extend(newl)    newcolorlist2 = []    for i in newcolorlist:        if i>1.:            newcolorlist2.append(1.)        elif i < 0:            newcolorlist2.append(0.)        else:            newcolorlist2.append(i)    shrunklist2 = [0 for i in range(int(len(newcolorlist2)/slicesize)+1)]    for j in range(len(newcolorlist)):        if shrunklist2[int(j/slicesize)] == 0:            shrunklist2[int(j/slicesize)] = newcolorlist2[j]        else:            shrunklist2[int(j/slicesize)] = int((shrunklist2[int(j/slicesize)] + newcolorlist2[j])/2.)    #shrunklist2 = [(l+m)/2. for l,m in zip(shrunklist2,shrunklist)]       newcolorlist2 = [int(i * 255.) for i in newcolorlist2]    return ((shrunklist2,newcolorlist2))
and a encode process,
    f =colorlist     for x in range(10):         returnlist = colorlistfract(f,int(len( colorlist )/4.))         newlist = recoverlist(returnlist,int(len( colorlist )/4.))         f = [((a*.5)+(b*.5)) for a,b in zip(newlist[1], colorlist )]
and a decode process using returnlist,
           for x in range(35):         newlist = recoverlist(returnlist,slicesize)         returnlist = colorlistfract(newlist[1],slicesize)
    print( colorlist, newlist)
1 note · View note
tbabb · 10 years ago
Photo
Tumblr media
Original Images.
Tumblr media
Original Encoded, notice the phase shift.
Tumblr media
Using Fourier Transform with 50% of list discarded.
Tumblr media
Using Fractal Compression with list of 100 transformations (forward / reverse , scale). Also using compressed “seed” for construction. Notice the artifacts. Notice the lack of phase shift.
Finally, Using Fractal Compression with list of 100 transformations (forward / reverse , scale). Also using random“seed” for construction.
http://pastebin.com/bTB0qa96
Tumblr media
0 notes
tbabb · 10 years ago
Photo
Tumblr media
Success! I have achieved Fractal in Fractal encoding. Now the color lists that accompany the complex points have been reduced from 1/8th of the pixels to a fractal that is 1/160th of the pixels.
http://pastebin.com/d47e6UNm
It should be theoretically possible to cover the whole 512x512 image with less than 200 points.
Another thing that could be done it to seek out sets that are smaller like 75 pixels that are predominately one color. They would only need a complex point and an color.
2 notes · View notes
tbabb · 10 years ago
Photo
Tumblr media
This Image is a list of 445 complex points with lists holding truncated Fourier information (like a JPEG). An interesting note is that because the points lie in the chaotic region you can just add the tiniest offset to the point and the image becomes unintelligible making for both simple and rigorous encryption. Right now I'm going to replace the Fourier information with Hutchinson style fractal compression (what I’ve been trying to do for years to the whole image) and I can see more rabbit holes that might take the process even further.
http://pastebin.com/NqiAmCer
replace the pickle.load function with a random point generator ;
    FDlist4 = []     for i in range(40000):         FDlist4.append(((random.uniform(.25,.75),random.uniform(.25,.75)),[])).
Dump the results to a pickle file to get a list started. There is just tons of room for improvement in this process.
0 notes
tbabb · 10 years ago
Photo
Tumblr media Tumblr media
Discrete Fourier Transform Image Primer
Here’s a rough overview of how the  Discrete Fourier Transform can be used in image compression.
First some modules and a function.
   import math,random
   from PIL import Image
   def Discrete _fourier_transform(intdir,x1):        MC = math.cos        MS = math.sin        MP = math.pi        m = len(x1)        x2 = [complex(0.,0.) for i in range(m)]
       for i in range(m):           arg = - intdir * 2.0 * MP * i / m            for k in range(m):                x2[i] += complex((x1[k].real * MC(k * arg) - x1[k].imag * MS(k * arg)),                                  (x1[k].real * MS(k * arg) + x1[k].imag * MC(k * arg)))
      if intdir == 1:            return [x2[i] / m for i in range(m)]
      else:            return x2
open an image.
   lena = Image.open('C:\\Python27\\atlantis.jpg')
Split into bands and resize
   lenaG , lenaR , lenaB =  lena.split()
   lenaR = lenaR.resize((100,100))
   lenaG = lenaG.resize((100,100))
   lenaB = lenaB.resize((100,100))
In this demo we go line by line.
   for j in range(100):        somelistR = []        somelistG = []        somelistB = []
       # Make complex lists for each image line.        for i in range(100):            somelistR.append(complex(lenaR.getpixel((j,i))/255.,0.))            somelistG.append(complex(lenaG.getpixel((j,i))/255.,0.))            somelistB.append(complex(lenaB.getpixel((j,i))/255.,0.))    
       #  We already know what the pre-image looks like so this is for the demo.
       [preimageR.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistR)]        [preimageG.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistG)]        [preimageB.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistB)]
       # Run the function in the forward direction.
       somelistR = Discret_fourier_transform(1,somelistR)        somelistG = Discret_fourier_transform(1,somelistG)        somelistB = Discret_fourier_transform(1,somelistB)
       # Now we will just average the end of the list and effectively
       # compress the list. If we comment out this region we can see
       # that the image is restore by the reverse function. We could
       # also add numbers to the list as a watermark.
       for i in range(40,100):            somelistG[i] = sum(somelistG)/len(somelistG)            somelistR[i] = sum(somelistR)/len(somelistR)            somelistB[i] = sum(somelistB)/len(somelistB)    
       #  Run the function in the reverse direction.
       somelistR = Discret_fourier_transform(-1,somelistR)        somelistG = Discret_fourier_transform(-1,somelistG)            somelistB = Discret_fourier_transform(-1,somelistB)
       # Put the picture back together from the real part of the complex list.
       # there is information in the complex part of image as well
       [postimageR.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistR)]        [postimageG.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistG)]            [postimageB.putpixel((j,k),int(l.real*255.)) for k,l in enumerate(somelistB)]
   # Merge the bands and save the images.
   preimg = Image.merge('RGB',(preimageR,preimageG,preimageB))    preimg.save('c:\\python27\\Discret_fourier_transform_preimg.png')
   postimg = Image.merge('RGB',(postimageR,postimageG,postimageB))    postimg.save('c:\\python27\\Discret_fourier_transform_postimg.png')
0 notes
tbabb · 10 years ago
Photo
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
Fractal by brute force
First I tried using the 60,60,60 grid with the new wonky fractal space I just made. I just saved images of 60x60 grids and used pillow to compare the rms of the fractal and the fractal multiplied by the image. I don’t know what I expect to find or why but I’m intrigued. So I think that 60x60x60 is limited I should just try a random approach and see whats lines up. The next program I wrote takes a point and iterates it 4k times fugues out how many pixels it coves in the image and makes a color histogram.So if the max of the color histogram is 4k and it covers 50 points that's your compression.
Our new image is “Atlantis”.
The first image is in the complex phase space of z**5 +c
http://pastebin.com/edcJT2Lz
The next two images are in the FunkyDootle phase space of z**5 + c
http://pastebin.com/PDLAL0eT
The problem with this approach other than its obvious time limits is that the numbers of pixels represented by the points have to grow progressively smaller in order to see the fine detail. Now I’m tying to use Discrete Fourier Transform in conjunction with this method. 
There may be a relationship between the DFT of the pixel values and the DFT of the complex points of the Julia sets. Maybe the cleverness needed to accomplish the ultimate fractal compression lies here. Like stardust sprinkled on a dynamic Julia sheet that grows the image organically.
(more later)
0 notes
tbabb · 10 years ago
Photo
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
For years I have been tinkering with the idea that an image might be represented by a single IFS with a minimal set of points. My efforts have  produced many interesting results but no magical IFS has yet fall from the picture itself. I moved to complex numbers because Julia sets are both rich in imagery and simple to construct. Most of my past explorations have gone something like this. First take your complex dynamical formula;
    z = z**2 + c
Pick a subset of space that you want to work in, say -1 to 1 for x and y. Than encode the pixel position in c.
    c = complex( ( float(x_position / len(x) ) - .5) * 2., ( float(y_position / len(y) ) - .5) * 2.)
A note here is that you can encode two images into a single complex array and do interesting things.
 than complex encode the pixel, a good one is ;
    new_pixel_number = complex( cmath.e**(old_pixel_number/255.), cmath.e**(old_pixel_number/255.) )
A note here is that you can encode two images into a single complex array and do interesting things.
set initial z as your pixel number.
    z =  new_pixel_number
than iterate the formulas a couple of thousand times and look at it. What you find is that the center gets darker but holds the z information forever. Most of the chaotic region holds some information like edges but loses color information. Other parts, as expected, just lose the image altogether.
This approach has lead to describing the fractal in terms of the the image instead of describing the image in terms of the fractal. So now I’v decided to stop trying to beat the fractal out the image and now I’m going to beat the fractal into the image.
(More to come)
0 notes
tbabb · 10 years ago
Photo
Tumblr media
z → z*z*z + c, z = [-1,1] + [-1,1]i + [-1,1]j, c= 0.6333333333333333 + .4i + .2j
http://pastebin.com/bNnDtuhs
0 notes