Esempio n. 1
0
File: McMaps.py Progetto: a1k0n/ants
def draw_line(image, point, neighbor, size):
    width, height = size
    center_point = (width//2, height//2)
    offset = (width//2 - point[0], height//2 - point[1])
    image = ImageChops.offset(image, offset[0], offset[1])
    draw = ImageDraw.Draw(image)
    to_point = ((neighbor[0] + offset[0]) % width, (neighbor[1] + offset[1]) % height)
    draw.line((center_point, to_point))
    return ImageChops.offset(image, -offset[0], -offset[1])
Esempio n. 2
0
def draw_line(image, point, neighbor, size):
    width, height = size
    center_point = (width//2, height//2)
    offset = (width//2 - point[0], height//2 - point[1])
    image = ImageChops.offset(image, offset[0], offset[1])
    draw = ImageDraw.Draw(image)
    to_point = ((neighbor[0] + offset[0]) % width, (neighbor[1] + offset[1]) % height)
    draw.line((center_point, to_point))
    return ImageChops.offset(image, -offset[0], -offset[1])
Esempio n. 3
0
def voronoi(players=4):
    width = randrange(64, 256)
    height = randrange(64, 256)
    point_count = randrange(players * 3, players * 6)
    min_dist = width * height / point_count
    print('%s, %s  %s %s' % (width, height, min_dist, sqrt(min_dist)))
    px, py = 0, 0
    points = []
    while min_dist > 100 and len(points) < point_count:
        while min_dist > 100:
            px, py = randrange(width), randrange(height)
            for nx, ny in points:
                if distance(px, py, nx, ny, width, height) < min_dist:
                    break
            else:
                break
            min_dist -= 1
        points.append((px, py))
    #for px, py in points:
    #    for nx, ny in points:
    #        print('(%s)-(%s) = %s' % ((px,py),(nx,ny),distance(px, py, nx, ny, width, height)))
    path = {}
    closest = {}
    for p_x, p_y in points:
        nearest = {}
        for n_x, n_y in points:
            if (p_x, p_y) != (n_x, n_y):
                dist = distance(p_x, p_y, n_x, n_y, width, height)
                nearest[dist] = (n_x, n_y)
        sorted = nearest.keys()
        sorted.sort()
        path[(p_x, p_y)] = [nearest[key] for key in sorted[:3]]
        closest[(p_x, p_y)] = sorted[0]
    image = Image.new('RGB', (width, height), BARRIER_COLOR)
    draw = ImageDraw.Draw(image)
    for point in points:
        image.putpixel(point, (0, 0, 0))
        size = int(sqrt(closest[point])) // 2 - 2
        draw.ellipse((point[0] - size, point[1] - size, point[0] + size,
                      point[1] + size),
                     fill=LAND_COLOR,
                     outline=LAND_COLOR)
    from_point = (width // 2, height // 2)
    for point, path_neighbors in path.items():
        offset = (width // 2 - point[0], height // 2 - point[1])
        image = ImageChops.offset(image, offset[0], offset[1])
        draw = ImageDraw.Draw(image)
        for neighbor in path_neighbors:
            to_point = ((neighbor[0] + offset[0]) % width,
                        (neighbor[1] + offset[1]) % height)
            draw.line((from_point, to_point),
                      width=randrange(3, 6),
                      fill=LAND_COLOR)
        image = ImageChops.offset(image, -offset[0], -offset[1])
    image = image.resize((width * 4, height * 4))
    image.save('voronoi.png')
Esempio n. 4
0
def voronoi(players=4):
    width = randrange(64, 256)
    height = randrange(64, 256)
    point_count = randrange(players*3, players*6)
    min_dist = width * height / point_count
    print('%s, %s  %s %s' % (width, height, min_dist, sqrt(min_dist)))
    px, py = 0, 0
    points = []
    while min_dist > 100 and len(points) < point_count:
        while min_dist > 100:
            px, py = randrange(width), randrange(height)
            for nx, ny in points:
                if distance(px, py, nx, ny, width, height) < min_dist:
                    break
            else:
                break
            min_dist -= 1
        points.append((px, py))
    #for px, py in points:
    #    for nx, ny in points:
    #        print('(%s)-(%s) = %s' % ((px,py),(nx,ny),distance(px, py, nx, ny, width, height)))
    path = {}
    closest = {}
    for p_x, p_y in points:
        nearest = {}
        for n_x, n_y in points:
            if (p_x, p_y) != (n_x, n_y):
                dist = distance(p_x, p_y, n_x, n_y, width, height)
                nearest[dist] = (n_x, n_y)
        sorted = nearest.keys()
        sorted.sort()
        path[(p_x, p_y)] = [nearest[key] for key in sorted[:3]]
        closest[(p_x, p_y)] = sorted[0]
    image = Image.new('RGB', (width, height), BARRIER_COLOR)
    draw = ImageDraw.Draw(image)
    for point in points:
        image.putpixel(point, (0,0,0))
        size = int(sqrt(closest[point]))//2 - 2
        draw.ellipse((point[0]-size, point[1]-size, point[0]+size, point[1]+size),
                fill=LAND_COLOR, outline=LAND_COLOR)
    from_point = (width//2, height//2)
    for point, path_neighbors in path.items():
        offset = (width//2 - point[0], height//2 - point[1])
        image = ImageChops.offset(image, offset[0], offset[1])
        draw = ImageDraw.Draw(image)
        for neighbor in path_neighbors:
            to_point = ((neighbor[0] + offset[0]) % width, (neighbor[1] + offset[1]) % height)
            draw.line((from_point, to_point), width=randrange(3,6), fill=LAND_COLOR)
        image = ImageChops.offset(image, -offset[0], -offset[1])
    image = image.resize((width*4, height*4))
    image.save('voronoi.png')
	def resizeImage(self, imagePath, width, height):
		outfile=imagePath+"_"+str(width)+"_"+str(height)
		if not os.path.isfile(imagePath):
			print imagePath + " does not exist"
			return None

		#if resized file already exists, return the same
		if os.path.isfile(outfile):
			return outfile

		try:
			size = (width,height)
			im = Image.open(imagePath)		
			if im.size[0]==self.reqImgWidth and im.size[1]==self.reqImgHeight:
				return imagePath
            		im.thumbnail(size, Image.ANTIALIAS)


			image_size = im.size
			thumb = im.crop( (0, 0, size[0], size[1]) )
			offset_x = max( (size[0] - image_size[0]) / 2, 0 )
			offset_y = max( (size[1] - image_size[1]) / 2, 0 )
			thumb = ImageChops.offset(thumb, offset_x, offset_y)

            		thumb.save(outfile, "JPEG")
			return outfile
		except IOError:
			print "IOError while resizing " + imagePath
			return None
Esempio n. 6
0
  def test_stereo(self):
    cam = camera.VidereCamera(open("wallcal.ini").read())
    #lf = Image.open("wallcal-L.bmp").convert("L")
    #rf = Image.open("wallcal-R.bmp").convert("L")
    for offset in [ 1, 10, 10.25, 10.5, 10.75, 11, 63]:
      lf = Image.open("snap.png").convert("L")
      rf = Image.open("snap.png").convert("L")
      rf = rf.resize((16 * 640, 480))
      rf = ImageChops.offset(rf, -int(offset * 16), 0)
      rf = rf.resize((640,480), Image.ANTIALIAS)
      for gradient in [ False, True ]:
        af = SparseStereoFrame(lf, rf, gradient)
        vo = VisualOdometer(cam)
        vo.find_keypoints(af)
        vo.find_disparities(af)
        error = offset - sum([d for (x,y,d) in af.kp]) / len(af.kp)
        self.assert_(abs(error) < 0.25) 

    if 0:
      scribble = Image.merge("RGB", (lf,rf,Image.new("L", lf.size))).resize((1280,960))
      #scribble = Image.merge("RGB", (Image.fromstring("L", lf.size, af0.lgrad),Image.fromstring("L", lf.size, af0.rgrad),Image.new("L", lf.size))).resize((1280,960))
      draw = ImageDraw.Draw(scribble)
      for (x,y,d) in af0.kp:
        draw.line([ (2*x,2*y), (2*x-2*d,2*y) ], fill = (255,255,255))
      for (x,y,d) in af1.kp:
        draw.line([ (2*x,2*y+1), (2*x-2*d,2*y+1) ], fill = (0,0,255))
def pad_image(image, **kwargs):
    'Pad an image to make it the same aspect ratio of the desired thumbnail.'

    img_width, img_height = image.size
    des_width, des_height = kwargs['size']
    if not (0.1 < float(des_height) / des_width < 10.0):
        return image  # Doesn't pad the image if the resize ratio is
                      # exaggerated.  Useful in django-filer admin.
    fit = (float(img_width) / des_width,
           float(img_height) / des_height)

    if fit[0] > fit[1]:
        new_image_size = (img_width, int(round(des_height * fit[0])))
        top = (new_image_size[1] - img_height) / 2
        left = 0
    elif fit[0] < fit[1]:
        new_image_size = (int(round(des_width * fit[1])), img_height)
        top = 0
        left = (new_image_size[0] - img_width) / 2
    else:
        return image

    try:
        # Converts the image to add an alpha layer.
        image = image.convert('RGBA')
        # Resizes the image.
        image = image.crop((0, 0, new_image_size[0], new_image_size[1]))
        # Adds an offset to center the image.
        new_image = ImageChops.offset(image, left, top)

        return new_image
    except:
        return image
Esempio n. 8
0
def distort(image_file, glitch = False):
        if glitch:
                glitch = 1
        else:
                glitch = 0
        x = Image.open(image_file, "r")
        x.load()
        red, green, blue = x.split()
        
        green = ImageChops.offset(green,
            glitch*random.randint(0,3),
            glitch*random.randint(0,3))
        
        blue = ImageChops.offset(ImageEnhance.Contrast(blue).enhance(.4),
            glitch*random.randint(0,5),
            glitch*random.randint(0,5))
        
        Image.merge("RGB", (red, green, blue)).save("vyntage_%s" %
                                                    image_file)
Esempio n. 9
0
def addup(ims,offset):
	##must be of len 2**m
	n=1
	while len(ims)>1:
		newims=[]
		for i in range(0,len(ims),2):
			#print 'offset = %d'%(-offset*n)
			newims.append(ImageChops.add(ims[i],ImageChops.offset(ims[i+1],offset*n,0),2,0))
		ims = newims
		n*=2
	return ims[0]
Esempio n. 10
0
def addup2(ims,offset):
	##must be of len 2**m
	
	n=len(ims)+1
	#do all the offsets
	ims = [ImageChops.offset(im,-offset*(n/2-i),0) for i,im in enumerate(ims)]
	
	#add all the images, two at a time to avoid overflow
	while len(ims)>1:		
		ims = [ImageChops.add(ims[i],ims[i+1],2,0) for i in range(0,len(ims),2)]

	return ims[0]
Esempio n. 11
0
def combine(ims,offset):
	
	n=len(ims)-1
	
	#do all the offsets
	ims = [ImageChops.offset(im,-offset*(n/2-i),0) for i,im in enumerate(ims)]
	
	#add all the images, two at a time to avoid overflow
	while len(ims)>1:		
		ims = [ImageChops.add(ims[i],ims[i+1],2,0) for i in range(0,len(ims),2)]
	
	#return the final result image
	return ims[0]
Esempio n. 12
0
        def getCategoryIcon(category):
            categoryIcons = Image.open(self.__basepath + 'categoryicons18px.png')
            #icon = Image.new('RGBA', (18,18), (255,255,255,0))

            categories = ('restaurant', 'bar', 'cafe', 'place', 'album', 'song', 'artist', 'film', 'tv_show',
                          'book', 'software', 'other')
            if category not in categories:
                categoryIndex = len(categories)-1
            else:
                categoryIndex = categories.index(category)
            print categoryIndex

            icon = ImageChops.offset(categoryIcons, -20*categoryIndex, 20)
            icon = icon.crop((0, 0, 18, 18))
            #icon.paste(categoryIcons, (20*categoryIndex, 20, (20*categoryIndex)+18, 38))
            return icon
Esempio n. 13
0
 def test_stereo_accuracy(self):
     fd = FeatureDetectorStar(300)
     ds = DescriptorSchemeSAD()
     for offset in [1, 10, 10.25, 10.5, 10.75, 11, 63]:
         lf = self.img640x480
         rf = self.img640x480
         rf = rf.resize((16 * 640, 480))
         rf = ImageChops.offset(rf, -int(offset * 16), 0)
         rf = rf.resize((640, 480), Image.ANTIALIAS)
         for gradient in [False, True]:
             af = SparseStereoFrame(lf,
                                    rf,
                                    gradient,
                                    feature_detector=fd,
                                    descriptor_scheme=ds)
             kp = [(x, y, d) for (x, y, d) in af.features() if (x > 64)]
             error = offset - sum([d for (x, y, d) in kp]) / len(kp)
             print error
             self.assert_(abs(error) < 0.25)
Esempio n. 14
0
def runAnimation(direction="out", stepsSpeed = 1):
	global motions, config
	run = True
	
	dirUnit = 1 * config.stroopSteps
	blockWidth = 1
	blockPos = 0
	blockDir = 1
	panelWidth = config.screenWidth /2
	panelHeight = config.screenHeight
	if (direction == "in") : dirUnit =  -1 * config.stroopSteps

	# need to add each text-image to a single composite
	# but move each side in or out each cycle

	while ( run == True) :
		for i in range(0,2) :
		 
			ref  = motions[i]
			image = ref[0]
			n = ref[1]
			side = ref[2]
			offset = ref[3]
			speed = ref[4]

			if(side == "Left") :
				motions[i][1] = n - dirUnit*config.stroopSteps
				xPos = 0
				xBlock = panelWidth - blockWidth - blockPos*blockDir
			if(side == "Right") :
				motions[i][1] = n + dirUnit*blockDir*config.stroopSteps
				xPos = panelWidth
				xBlock = 0 + blockPos

			# crop and load
			invertedBlock = ImageChops.offset(image,int(n),0)
			invertedBlock = invertedBlock.crop((0,0,panelWidth,panelHeight))
			config.render(invertedBlock,xPos,0,panelWidth,panelHeight,False)

		time.sleep(config.stroopSpeed)
Esempio n. 15
0
 def test_feature_detectors(self):
     L = self.img640x480
     R = ImageChops.offset(L, -3, 0)
     for fdt in [
             FeatureDetectorFast, FeatureDetectorStar, FeatureDetectorHarris
     ]:
         feat = []
         for count in range(30, 300, 5):
             fd = fdt(count)
             frame = SparseStereoFrame(L,
                                       R,
                                       feature_detector=fd,
                                       descriptor_scheme=None)
             prev_feat, feat = feat, frame.features()
             # At least half the number of features requested
             self.assert_((count / 2) < len(feat))
             # Should never return too many features - too few is OK because of stereo
             self.assert_(len(feat) <= count)
             # Should have same or more features with greater count
             self.assert_(len(prev_feat) <= len(feat))
             # Previous feature call is always a sublist of this feature call
             self.assert_(feat[:len(prev_feat)] == prev_feat)
Esempio n. 16
0
File: pat.py Progetto: anthonyjb/pat
 def to_image(self, full_repeat=False):
     """
     Convert the pattern to an image. Optional you can specify to convert
     the image to a full repeat (based on the drop value).
     """
     
     # Calculate the repeats needed if creating a full repeat
     repeats = 1
     if full_repeat:
         repeats = int(self.size[1] / self.drop)
     
     # Create the image
     image = Image.new('RGB', (self.size[0] * repeats, self.size[1]))
     pixels = [self.channels[bit] for bit in self.bitmap]
     pattern = Image.new('RGB', self.size)
     pattern.putdata(pixels)
     
     # Paste the pattern on to the image
     for repeat in range(0, repeats):
         image.paste(pattern, (self.size[0] * repeat, 0))
         pattern = ImageChops.offset(pattern, 0, self.drop)
     
     return image
Esempio n. 17
0
    def run(self):
        while True:
            self.imagePath = self.queueIMG.get()
            self.imageDir, self.imageName = os.path.split(self.imagePath)
            self.thumbDir = os.path.join(self.imageDir, "@eaDir",
                                         self.imageName)
            print "\t[-]Now working on %s" % (self.imagePath)
            if os.path.isfile(os.path.join(self.thumbDir, xlName)) != 1:
                if os.path.isdir(self.thumbDir) != 1:
                    try:
                        os.makedirs(self.thumbDir)
                    except:
                        continue

                #Following if statements converts raw images using dcraw first
                if os.path.splitext(self.imagePath)[1].lower() == ".cr2":
                    self.dcrawcmd = "dcraw -c -b 8 -q 0 -w -H 5 '%s'" % self.imagePath
                    self.dcraw_proc = subprocess.Popen(shlex.split(
                        self.dcrawcmd),
                                                       stdout=subprocess.PIPE)
                    self.raw = StringIO(self.dcraw_proc.communicate()[0])
                    self.image = Image.open(self.raw)
                else:
                    self.image = Image.open(self.imagePath)

                ###### Check image orientation and rotate if necessary
                ## code adapted from: http://www.lifl.fr/~riquetd/auto-rotating-pictures-using-pil.html
                self.exif = self.image._getexif()

                if not self.exif:
                    return False

                self.orientation_key = 274  # cf ExifTags
                if self.orientation_key in self.exif:
                    self.orientation = self.exif[self.orientation_key]

                    rotate_values = {3: 180, 6: 270, 8: 90}

                    if self.orientation in rotate_values:
                        self.image = self.image.rotate(
                            rotate_values[self.orientation])

                #### end of orientation part

                self.image.thumbnail(xlSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir, xlName),
                                quality=90)
                self.image.thumbnail(lSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir, lName), quality=90)
                self.image.thumbnail(bSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir, bName), quality=90)
                self.image.thumbnail(mSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir, mName), quality=90)
                self.image.thumbnail(sSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir, sName), quality=90)
                self.image.thumbnail(pSize, Image.ANTIALIAS)
                # pad out image
                self.image_size = self.image.size
                self.preview_img = self.image.crop((0, 0, pSize[0], pSize[1]))
                self.offset_x = max((pSize[0] - self.image_size[0]) / 2, 0)
                self.offset_y = max((pSize[1] - self.image_size[1]) / 2, 0)
                self.preview_img = ImageChops.offset(self.preview_img,
                                                     self.offset_x,
                                                     self.offset_y)
                self.preview_img.save(os.path.join(self.thumbDir, pName),
                                      quality=90)
            self.queueIMG.task_done()
Esempio n. 18
0
def offset(image, horizontal_offset, vertical_offset=None):
    return ImageChops.offset(image, horizontal_offset, vertical_offset)
Esempio n. 19
0
    def run(self):
        while True:
            self.imagePath=self.queueIMG.get()
            self.imageDir,self.imageName = os.path.split(self.imagePath)
            self.thumbDir=os.path.join(self.imageDir,"@eaDir",self.imageName)
            print "\t[-]Now working on %s" % (self.imagePath)
            if os.path.isfile(os.path.join(self.thumbDir,xlName)) != 1:
                if os.path.isdir(self.thumbDir) != 1:
                    try:os.makedirs(self.thumbDir)
                    except:continue
                
                #Following if statements converts raw images using dcraw first
                if os.path.splitext(self.imagePath)[1].lower() == ".cr2":
                    self.dcrawcmd = "dcraw -c -b 8 -q 0 -w -H 5 '%s'" % self.imagePath
                    self.dcraw_proc = subprocess.Popen(shlex.split(self.dcrawcmd), stdout=subprocess.PIPE)
                    self.raw = StringIO(self.dcraw_proc.communicate()[0])
                    self.image=Image.open(self.raw)
                else:
                    self.image=Image.open(self.imagePath)

                ###### Check image orientation and rotate if necessary
                ## code adapted from: http://www.lifl.fr/~riquetd/auto-rotating-pictures-using-pil.html
                self.exif = self.image._getexif()
    
                if not self.exif:
                    return False
            
                self.orientation_key = 274 # cf ExifTags
                if self.orientation_key in self.exif:
                    self.orientation = self.exif[self.orientation_key]
            
                    rotate_values = {
                        3: 180,
                        6: 270,
                        8: 90
                    }
            
                    if self.orientation in rotate_values:
                        self.image=self.image.rotate(rotate_values[self.orientation])

                #### end of orientation part

                self.image.thumbnail(xlSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir,xlName), quality=90)
                self.image.thumbnail(lSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir,lName), quality=90)
                self.image.thumbnail(bSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir,bName), quality=90)
                self.image.thumbnail(mSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir,mName), quality=90)
                self.image.thumbnail(sSize, Image.ANTIALIAS)
                self.image.save(os.path.join(self.thumbDir,sName), quality=90)
                self.image.thumbnail(pSize, Image.ANTIALIAS)
                # pad out image
                self.image_size = self.image.size
                self.preview_img = self.image.crop((0, 0, pSize[0], pSize[1]))
                self.offset_x = max((pSize[0] - self.image_size[0]) / 2, 0)
                self.offset_y = max((pSize[1] - self.image_size[1]) / 2, 0)
                self.preview_img = ImageChops.offset(self.preview_img, self.offset_x, self.offset_y)
                self.preview_img.save(os.path.join(self.thumbDir,pName), quality=90)
            self.queueIMG.task_done()
Esempio n. 20
0
 def offset(self, xoffset, yoffset=None):
     "(deprecated) Offset image in horizontal and/or vertical direction"
     import ImageChops
     return ImageChops.offset(self, xoffset, yoffset)
Esempio n. 21
0
def offset(image, horizontal_offset, vertical_offset=None):
    return ImageChops.offset(image, horizontal_offset, vertical_offset)
Esempio n. 22
0
i1 = Image.eval(small, bw)
i1.save("/tmp/i1.jpg")
print "I1, orig, saved."
i2 = ImageChops.duplicate(i1)
marked = Image.eval(marked, bw)

merge = i2

# calculate spread that works well with your scaling factor
spread = int(round(i1.size[0] / (scaling_factor * 75.)))

# wherever there's a dark pixel, darken all pixels within spread pixels
for x in range(-spread, spread, 1):
    for y in range(-spread, spread, 1):
        print spread, x, y
        newi = ImageChops.offset(i2, x, y)
        merge = ImageChops.darker(merge, newi)
i2 = merge
i2.save("/tmp/i2.jpg")
print "I2, mask, saved"
i3 = i2.resize((i1.size[0], i1.size[1]))
i3.save("/tmp/i3.jpg")
print "I3 saved"

i4 = Image.eval(i3, bw)

rot = i1.rotate(.5)
i5 = ImageChops.darker(rot, i4)

rot = i1.rotate(1.)
i6 = ImageChops.darker(rot, i4)
Esempio n. 23
0
def main():
    arg_len = len(sys.argv)
    if arg_len < 2:
        print('Usage: spectrum.py <input file> <(optional) output file>')
    if arg_len >= 2:
        input_filename = sys.argv[1]
        output_filename = input_filename + '.mp4'
    if arg_len == 3:
        output_filename = sys.argv[2]

    call(['ffmpeg',
        '-i', input_filename,
        input_filename + '.wav'
        ])

    rate, data = wavfile.read(input_filename + '.wav')
    data = data.transpose()
    L = data[0]
    R = data[1]

    im = Image.new("RGBA", IMAGE_SIZE, BACKGROUND)
    draw = ImageDraw.Draw(im)

    line = Image.new("RGBA", (1, LINE_HEIGHT))
    line_draw = ImageDraw.Draw(line)
    for y in xrange(LINE_HEIGHT):
        fill = hsv2rgb(float(y)/LINE_HEIGHT*120,1,1)
        # fill = interpolate(float(y)/LINE_HEIGHT, LINE_START, LINE_END)
        line_draw.point((0,y), fill = fill)

    try:
        for i, fft in enumerate(build_fft(L)):
            x_offset = 0
            y_offset = 5
            width, height = im.size
            im = ImageChops.offset(im, x_offset, -y_offset)

            enhancer = ImageEnhance.Brightness(im)
            im = enhancer.enhance(.98)

            #pix = im.load()
            draw = ImageDraw.Draw(im)
            draw.rectangle((0, 0, x_offset, height), BACKGROUND)
            draw.rectangle((0, height + y_offset, width, height), BACKGROUND)

            prev = None
            for x, y in enumerate(fft):
                # y = math.sqrt(abs(y.real) * 1e2) * 10
                # y = abs(y.real) * 10
                y = math.log(abs(y.real) + 1) * 35
                # print(y)
                y = min(LINE_HEIGHT, y) 
                #fill=hsv2rgb((i*3) % 360, 1, 1)
                #fill = (255-int(y*1.3),)*3
                #print(fill)
                #draw.line((x_, height, x_, height-y), fill=fill) #interpolate(float(x)/nFFT, LINE_START, LINE_END))
                from_box = (0, LINE_HEIGHT - int(y), 1, LINE_HEIGHT)
                region = line.crop(from_box)

                x = (x + nFFT/2) % nFFT
                x += (im.size[0] - nFFT) / 2
                # y_bot = height - (nFFT/2 - x/2) # Slanty
                y_bot = height

                to_box = (x, y_bot - int(y), x+1, y_bot)

                #to_box = (0, height - int(y) - (nFFT - x), 1, height - (nFFT - x))
                im.paste(region, to_box)

                if prev:
                    draw.line((x-1, y_bot - prev, x, y_bot - y), fill=(0,0,0,0))
                prev = y
            im.save('tmp/%07d.png' % i)
    except KeyboardInterrupt:
        pass
    call(["ffmpeg",
            "-y",
            "-i", input_filename,
            "-shortest",
            "-r", str(FPS),
            "-i", 'tmp/%07d.png',
            "-pix_fmt", "yuv420p",
            "-r", str(FPS),
            output_filename])

    if  path.exists(output_filename):
        os.system('rm tmp/*')
    os.unlink(input_filename + '.wav')
Esempio n. 24
0
"""
Program name: image_offset_1.py
Objective: Make a reduced copy of an image.

Keywords: Image, offset, jpg,
============================================================================79
 
Explanation: Simple syntax to change image size 

Author:          Mike Ohlson de Fine

"""
# image_offset_1.py
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import Image
import ImageChops

im_1 = Image.open("/constr/pics1/canary_a.jpg")

# adjust width and height to desired size
dx = 200
dy = 300

im_2 = ImageChops.offset(im_1, dx, dy)
im_2.save("/constr/picsx/canary_2.jpg")

Esempio n. 25
0
def main():
    arg_len = len(sys.argv)
    if arg_len < 2:
        print('Usage: spectrum.py <input file> <(optional) output file>')
    if arg_len >= 2:
        input_filename = sys.argv[1]
        output_filename = input_filename + '.mp4'
    if arg_len == 3:
        output_filename = sys.argv[2]

    call(['ffmpeg', '-i', input_filename, input_filename + '.wav'])

    rate, data = wavfile.read(input_filename + '.wav')
    data = data.transpose()
    L = data[0]
    R = data[1]

    im = Image.new("RGBA", IMAGE_SIZE, BACKGROUND)
    draw = ImageDraw.Draw(im)

    line = Image.new("RGBA", (1, LINE_HEIGHT))
    line_draw = ImageDraw.Draw(line)
    for y in xrange(LINE_HEIGHT):
        fill = hsv2rgb(float(y) / LINE_HEIGHT * 120, 1, 1)
        # fill = interpolate(float(y)/LINE_HEIGHT, LINE_START, LINE_END)
        line_draw.point((0, y), fill=fill)

    try:
        for i, fft in enumerate(build_fft(L)):
            x_offset = 0
            y_offset = 5
            width, height = im.size
            im = ImageChops.offset(im, x_offset, -y_offset)

            enhancer = ImageEnhance.Brightness(im)
            im = enhancer.enhance(.98)

            #pix = im.load()
            draw = ImageDraw.Draw(im)
            draw.rectangle((0, 0, x_offset, height), BACKGROUND)
            draw.rectangle((0, height + y_offset, width, height), BACKGROUND)

            prev = None
            for x, y in enumerate(fft):
                # y = math.sqrt(abs(y.real) * 1e2) * 10
                # y = abs(y.real) * 10
                y = math.log(abs(y.real) + 1) * 35
                # print(y)
                y = min(LINE_HEIGHT, y)
                #fill=hsv2rgb((i*3) % 360, 1, 1)
                #fill = (255-int(y*1.3),)*3
                #print(fill)
                #draw.line((x_, height, x_, height-y), fill=fill) #interpolate(float(x)/nFFT, LINE_START, LINE_END))
                from_box = (0, LINE_HEIGHT - int(y), 1, LINE_HEIGHT)
                region = line.crop(from_box)

                x = (x + nFFT / 2) % nFFT
                x += (im.size[0] - nFFT) / 2
                # y_bot = height - (nFFT/2 - x/2) # Slanty
                y_bot = height

                to_box = (x, y_bot - int(y), x + 1, y_bot)

                #to_box = (0, height - int(y) - (nFFT - x), 1, height - (nFFT - x))
                im.paste(region, to_box)

                if prev:
                    draw.line((x - 1, y_bot - prev, x, y_bot - y),
                              fill=(0, 0, 0, 0))
                prev = y
            im.save('tmp/%07d.png' % i)
    except KeyboardInterrupt:
        pass
    call([
        "ffmpeg", "-y", "-i", input_filename, "-shortest", "-r",
        str(FPS), "-i", 'tmp/%07d.png', "-pix_fmt", "yuv420p", "-r",
        str(FPS), output_filename
    ])

    if path.exists(output_filename):
        os.system('rm tmp/*')
    os.unlink(input_filename + '.wav')
Esempio n. 26
0
def differ(im,off): return ImageChops.difference(im,ImageChops.offset(im,off,0))


#find the median contrast at each pixel in each of the 20 shiftadded photos
ds = [ImageChops.add(differ(im,1),differ(im,-1),2,0).filter(ImageFilter.MedianFilter(11)) for im in ims]
Esempio n. 27
0
import requests
import Image, ImageChops


URL="http://*****:*****@www.pythonchallenge.com/pc/return/mozart.gif"
proxy = {
    'http': 'child-prc.intel.com:913',
    'https': 'child-prc.intel.com:913',
}

IMG_NAME = r"16.gif"

r = requests.get(URL, proxies=proxy,) #auth=HTTPBasicAuth(USERNAME, PASSWORD))
r.raise_for_status()
with open(IMG_NAME, "wb") as handle:
        handle.write(r.content)

magic = chr(195) # pink color
im = Image.open(IMG_NAME)
width, height = im.size

for y in range(height):
    crop_zone = 0, y, width, y+1
    row = im.crop(crop_zone)
    bs = row.tostring()
    i = bs.index(magic)
    row = ImageChops.offset(row, -i)
    im.paste(row, crop_zone)

im.save('16-gen.gif')
Esempio n. 28
0
import zlib
import Image
import ImageChops
import struct
import sys

offset = (128, 128)

if not len(sys.argv)>1:
	print "Rata puuttuu, hölö!"
	sys.exit(1)
	
i = Image.open(sys.argv[1])
o = open(sys.argv[1].replace(".png",".trk"),"wb")

i = ImageChops.offset(i, offset[0], offset[1])

"""
last = None
runlen = 0
bytes = 0
compressed = ""
for y in range(0,i.size[1]):
    for x in range(0,i.size[0]):
        p = i.getpixel((x,y))
        if p == last and runlen<255:
            runlen += 1
        else:
            if runlen:
                compressed += chr(p | 0x80) + chr(runlen)
            else: