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
Ejemplo n.º 2
1
def genVideoThumb(videofile, imagefile):
    (width, height) = get_video_size(videofile)
    frame_step = int(100 / THUMB_FRAME_COUNT)
    ratio = float(width) / float(height)
    if width > LIBRARYFILE_THUMB_WIDTH:
        width = LIBRARYFILE_THUMB_WIDTH
        height = int(width / ratio)
    if height > LIBRARYFILE_THUMB_HEIGHT:
        height = LIBRARYFILE_THUMB_HEIGHT
        width = int(height * ratio)
    width_offset = (LIBRARYFILE_THUMB_WIDTH - width) / 2
    height_offset = int((LIBRARYFILE_THUMB_HEIGHT - height) / 2)
    new_image = pil.new("RGB", (LIBRARYFILE_THUMB_WIDTH * THUMB_FRAME_COUNT, LIBRARYFILE_THUMB_HEIGHT))
    for i in range(THUMB_FRAME_COUNT):
        framefile = "%s%d.jpg" % (imagefile, i)
        # TODO: fix keyframing issue (perhaps flvtool2?)
        os.system(
            "ffmpegthumbnailer -i %s -o %s -t %d%% -q %d -s %d"
            % (videofile, framefile, i * frame_step, JPEG_QUALITY, width)
        )
        img = pil.open(framefile)
        new_image.paste(img, (LIBRARYFILE_THUMB_WIDTH * i + width_offset, height_offset))
        os.remove(framefile)
    new_image.save(imagefile)
    return True
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()
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def hide(bytes, bitmap, ext='sae'):
    """
        Hides the given bytes in the supplied bitmap.
        * bytes variable length byte sequence
        * bitmap bitmap file
    """
    
    image = Image.open(bitmap)
    out = Image.new(image.mode, image.size, None)
    
    pixels = to_pixels(image)
    bits = to_bits(bytes)
    
    finished = False
    
    for x, y, pixel in pixels:
        r, g, b = pixel
        
        bit, finished = move(bits, finished)
        r = r if bit is None else (r & ~1) | bit  
        
        bit, finished = move(bits, finished)
        g = g if bit is None else (g & ~1) | bit
        
        bit, finished = move(bits, finished)
        b = b if bit is None else (b & ~1) | bit

        out.putpixel((x, y), (r, g, b))
        
    name = bitmap.name + '.' + ext
    with open(name, "wb") as target:
        out.save(target, "BMP")
Ejemplo n.º 6
0
def apply_watermark(im, mark, position, opacity=1):
    """Adds a watermark to an image."""
    if opacity < 1:
        mark = reduce_opacity(mark, opacity)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new('RGBA', im.size, (0,0,0,0))
    if position == 'tile':
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == 'scale':
        # scale, but preserve the aspect ratio
        ratio = min(
            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
    elif position == 'bd': #en bas a droite
        x = im.size[0]-mark.size[0]
        y = im.size[1]-mark.size[1]
        layer.paste(mark, (x, y))
    else:
        layer.paste(mark, position)
    # composite the watermark with the layer
    return Image.composite(layer, im, layer)
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"
Ejemplo n.º 8
0
    def from_data_with_min_max(cls, slug, data, extent, min_value, max_value, cdict=None):
        """
        Create GeoImage from slug and data.
        """
        tmp_base = tempfile.mktemp()
        #print('tmp_base: %s' % tmp_base)
        #print('step 1')
        # Step 1: save png + pgw in RD
        if cdict is None:
            cdict = {
                'red': ((0.0, 51./256, 51./256),
                        (0.5, 237./256, 237./256),
                        (1.0, 83./256, 83./256)),
                'green': ((0.0, 114./256, 114./256),
                          (0.5, 245./256, 245./256),
                          (1.0, 83./256, 83./256)),
                'blue': ((0.0, 54./256, 54./256),
                         (0.5, 170./256, 170./256),
                         (1.0, 83./256, 83./256)),
                }
        colormap = mpl.colors.LinearSegmentedColormap('something', cdict, N=1024)
        normalize = mpl.colors.Normalize(vmin=min_value, vmax=max_value)
        rgba = colormap(normalize(data), bytes=True)
        #rgba[:,:,3] = np.where(rgba[:,:,0], 153 , 0)
        if 'depth' in slug:
            # Make transparent where depth is zero or less
            rgba[:,:,3] = np.where(np.greater(data, 0), 255, 0)
        Image.fromarray(rgba).save(tmp_base + '.png', 'PNG')

        write_pgw(tmp_base + '.pgw', extent)

        return cls.from_rd_png(tmp_base, slug, extent)
Ejemplo n.º 9
0
def write_image(img, fname, apply_gamma=False):
    """Save a float-3 numpy array image to a file.

    Supported formats: PNG, JPEG, and others; see PIL docs for more.

    Image can be 3-channel, which is interpreted as RGB, or can be 1-channel,
    which is greyscale.

    Can optionally specify that the image should be gamma-encoded prior to
    writing it out; this should be done if the image contains linear pixel
    values, to make the image look "normal".

    Args:
        img: Numpy image array data.
        fname: Path of file to save to; the extension specifies the format.
        apply_gamma: (Optional) apply gamma to the image prior to writing it.
    """
    if apply_gamma:
        img = apply_lut_to_image(img, DEFAULT_GAMMA_LUT)
    (h, w, chans) = img.shape
    if chans == 3:
        Image.fromarray((img * 255.0).astype(numpy.uint8), "RGB").save(fname)
    elif chans == 1:
        img3 = (img * 255.0).astype(numpy.uint8).repeat(3).reshape(h,w,3)
        Image.fromarray(img3, "RGB").save(fname)
    else:
        raise its.error.Error('Unsupported image type')
Ejemplo n.º 10
0
def partC():
	mag_image = Image.new('L', (256, 256))
	pix_mag = mag_image.load()
	for y in xrange(256):
		for x in xrange(256):
			pix_mag[y,x] =( sin((2*pi*2*x)/256)*127)+127
	mag_image.show()
	mag_image=mag_image.rotate(45)

	mag_image.show()
	mag_image.save("partC.png")
	f = []
	for y in xrange(256):
		f.append([])
		for x in xrange(256):
			f[y].append(mag_image.getpixel((y,x)))
	sp = np.fft.fft2(f)
	mag_image = Image.new('L', (256, 256))
	pix_mag = mag_image.load()
	for y in xrange(256):
		for x in xrange(256):
			mag = sqrt(sp[y][x].real**2+sp[y][x].imag**2)
			pix_mag[x,y] = (mag*127)+127
	mag_image.show()
	mag_image.save("F of partC.png")
Ejemplo n.º 11
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
Ejemplo n.º 12
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!'
Ejemplo n.º 13
0
    def prepare(self, filename, bgcolor = background_default, chatty = chatty_default):
        """
        Prepare a large image for tiling.
        
        Load an image from a file. Resize the image so that it is square,
        with dimensions that are an even power of two in length (e.g. 512,
        1024, 2048, ...). Then, return it.
        """

        src = Image.open(filename)
        self.orig_size = src.size

        self.new_size = (1, 1)

        while self.new_size[0] < src.size[0] or self.new_size[1] < src.size[1]:
            self.new_size = (self.new_size[0] * 2, self.new_size[1] * 2)
        
        img = Image.new('RGBA', self.new_size)
        img.paste("#" + bgcolor)
        
        src.thumbnail(self.new_size, scaling_filter)
        img.paste(src, (int((self.new_size[0] - src.size[0]) / 2),
                        int((self.new_size[1] - src.size[1]) / 2)))
        
        return img
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
def export_icon(icon, size, filename, font, color):
    image = Image.new("RGBA", (size, size), color=(0,0,0,0))

    draw = ImageDraw.Draw(image)

    # Initialize font
    font = ImageFont.truetype(font, size)

    # Determine the dimensions of the icon
    width,height = draw.textsize(icons[icon], font=font)

    draw.text(((size - width) / 2, (size - height) / 2), icons[icon],
            font=font, fill=color)

    # Get bounding box
    bbox = image.getbbox()

    if bbox:
        image = image.crop(bbox)

    borderw = int((size - (bbox[2] - bbox[0])) / 2)
    borderh = int((size - (bbox[3] - bbox[1])) / 2)

    # Create background image
    bg = Image.new("RGBA", (size, size), (0,0,0,0))

    bg.paste(image, (borderw,borderh))

    # Save file
    bg.save(filename)
 def __init__(self, width, height=None):
     '''
     Takes either a single string for a filename, or width and
     height of an empty picture.
     '''
     if height:
         self.image = Image.new('RGB', (width, height))
         self.title = 'Picture'
         self.width = width
         self.height = height
     else:
         self.image = Image.open(width) # actually filename
         self.title = width
         self.width, self.height = self.image.size
     # Default values for pen
     self.pen_color = (0, 0, 0)
     self.pen_position = (0, 0)
     self.pen_width = 1
     self.pen_rotation = 0
     # Pixel data of the image
     self.pixel = self.image.load()
     # Draw object of the image
     self.draw = ImageDraw.Draw(self.image)
     # The main window, and associated widgets.
     self.root = None
     self.canvas = None
Ejemplo n.º 17
0
 def _createIcon(self, nom, extensio):        
     ''' Creates an Icon for the shape 
     
       PARAMETERS
          nom      :  Name of the file without extension
          extensio: Extension 
          
       RETURNS
          Returns (sizex, sizey)
     '''        
     # create an icon 22x22 WITHOUT TRANSPARENCY             
     try:
         img = Image.open(nom + extensio)
     except:
         # Yes, I need to detect the error type ... maybe in the next version
         raise self.Image2DiaErrors(4)
         
     midax, miday = img.size   
     # Create a white background to skip 'bad transparency effect'
     icona = Image.new("RGB",(22,22),(255,255,255))     
     # Aspect Ratio
     novaMida = (30, 30 *miday/midax)
     img.thumbnail([22, 22], Image.ANTIALIAS)
     elformat = img.format
     
     center = ( (22 - img.size[0])/2, (22-img.size[1])/2 )
     icona.paste(img, center, img)
     
     try:
         icona.save('{0:>s}-icon.png'.format(nom), elformat, quality=90, optimize=1)
     except:
         icona.save("{0:>s}-icon.png".format(nom), elformat, quality=90)
         
     # img.close            
     return novaMida
Ejemplo n.º 18
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))
Ejemplo n.º 19
0
 def on_stitch(self,*args):
     self.stat("Generating stitched image...")
     x1,y1,x2,y2=[self.adj_x1.value,self.adj_y1.value,\
                  self.adj_x2.value,self.adj_y2.value]
     squish=self.adj_squish.value
     workwith=[]
     for fname in os.listdir(self.folder):
         if ".jpg" in fname or ".bmp" in fname \
                or ".png" in fname or ".tif" in fname:
             if not "stitched" in fname and \
                not self.fname in fname:
                 workwith.append(fname)
                 print "I SEE:",self.folder,fname
     workwith.sort()
     im=Image.new("RGB",((x2-x1)*len(workwith),y2-y1))
     try:os.mkdir(self.folder+"/stitched/")
     except:pass #folder there already
     for i in range(len(workwith)):
         print "Loading",workwith[i]
         im2=Image.open(self.folder+workwith[i])
         im2=im2.crop((x1,y1,x2,y2))
         if self.togglebutton2.get_active()==True:
             self.stat("saving %03d_"%i+self.fname+"...")
             im2.save(self.folder+"/stitched/%03d_"%i+self.fname,quality=90)
         im.paste(im2,(i*(x2-x1),0))
     self.stat("saving large image...")
     im.save(self.folder+"/stitched/"+self.fname,quality=90)
     im=im.resize((im.size[0]/squish,im.size[1]),Image.ANTIALIAS)
     im.save(self.folder+"/stitched/squished_"+self.fname,quality=90)
     f=open("stitchlog.txt",'w')
     f.write(str([x1,y1,x2,y2,self.imfilename]))
     f.close()
     print "DONE"             
     self.stat("COMPLETE!!! Launching folder containing stitched images...")   
     os.startfile(self.folder+"/stitched/")
Ejemplo n.º 20
0
def toimage(im):
    if hasattr(im, "toUtf8"):
        # FIXME - is this really the best way to do this?
        im = unicode(im.toUtf8(), "utf-8")
    if Image.isStringType(im):
        im = Image.open(im)
    return ImageQt(im)
Ejemplo n.º 21
0
def _getBounds(size, glDispID, filename, scale, rotation, partRotation):
    
    # Clear the drawing buffer with white
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    
    # Draw the piece in black
    glColor3f(0, 0, 0)
    adjustGLViewport(0, 0, size, size)
    rotateToView(rotation, scale)
    rotateView(*partRotation)

    glCallList(glDispID)

    # Use PIL to find the image's bounding box (sweet)
    pixels = glReadPixels(0, 0, size, size, GL_RGB,  GL_UNSIGNED_BYTE)
    img = Image.fromstring("RGB", (size, size), pixels)
    
    bg = bgCache.setdefault(size, Image.new("RGB", img.size, (255, 255, 255)))
    box = ImageChops.difference(img, bg).getbbox()

    if box is None:
        return (0, 0, 0, 0, 0, 0)  # Rendered entirely out of frame

#    if filename:
#        import os
#        rawFilename = os.path.splitext(os.path.basename(filename))[0]
#        img.save("C:\\lic\\tmp\\%s_%dx%d.png" % (rawFilename, box[2] - box[0], box[3] - box[1]))
#        print filename + "box: " + str(box if box else "No box = shit")

    # Find the bottom left corner inset, used for placing PLIItem quantity labels
    data = img.load()
    leftInset = _getLeftInset(data, size, box[1])
    bottomInset = _getBottomInset(data, size, box[0])
    return box + (leftInset - box[0], bottomInset - box[1])
Ejemplo n.º 22
0
 def onSave(self):
     file_opt = options = {}
     options['filetypes'] = [('Image Files', '*.tif *.jpg *.png')]
     options['initialfile'] = 'myImage.jpg'
     options['parent'] = self.parent
     fname = tkFileDialog.asksaveasfilename(**file_opt)
     Image.fromarray(np.uint8(self.Ilast)).save(fname)
Ejemplo n.º 23
0
Archivo: Sheet.py Proyecto: Val9/jasy
    def write(self, filename, debug=False):

        if Image is None:
            raise JasyError("Missing PIL to create sprite sheets")

        img = Image.new('RGBA', (self.width, self.height))
        draw = ImageDraw.Draw(img)

        #draw.rectangle((0, 0, self.width, self.height), fill=(255, 255, 0, 255))

        # Load images and pack them in
        for block in self.blocks:
            res = Image.open(block.image.src)

            x, y = block.fit.x, block.fit.y
            if block.rotated:
                debug('%s is rotated' % block.image.src)
                res = res.rotate(90)

            img.paste(res, (x, y))
            del res

            if debug:
                x, y, w, h = block.fit.x, block.fit.y, block.w, block.h
                draw.rectangle((x, y , x + w , y + h), outline=(0, 0, 255, 255) if block.rotated else (255, 0, 0, 255))

        if debug:
            for i, block in enumerate(self.packer.getUnused()):
                x, y, w, h = block.x, block.y, block.w, block.h
                draw.rectangle((x, y , x + w , y + h), fill=(255, 255, 0, 255))

        img.save(filename)
Ejemplo n.º 24
0
def getHorizontalAngleForText(image):
    width, height = image.size
    longest_axis = math.sqrt(width ** 2 + height ** 2)
    collage = Image.new('RGBA', (longest_axis, longest_axis), 'white')
    test_image = image.copy().convert('RGBA')
    y_to_paste = (longest_axis - test_image.size[1]) / 2
    x_to_paste = (longest_axis - test_image.size[0]) / 2
    original_paste = collage.copy()
    original_paste.paste(test_image, (x_to_paste, y_to_paste), test_image)
    previous_text_begin = getTextBeginHeight(original_paste)
    paste_image = original_paste.copy()
    angle = 0
    while angle > -360:
        current_text_begin = getTextBeginHeight(paste_image)
        if previous_text_begin > current_text_begin or current_text_begin == -1:
            break
        previous_text_begin = getTextBeginHeight(paste_image)
        angle -=5
        paste_image = original_paste.rotate(angle)
        collage = Image.new('RGBA', paste_image.size, 'white')
        collage.paste(paste_image, (0,0), paste_image)
        paste_image = collage
    if angle:
        return angle + 5
    return angle
Ejemplo n.º 25
0
    def getPygImage(self, th = False, color = 0):
        img = self.getImage()
        w = self.width
        h = self.height
        if False == th:
            m = self.mode
            d = img.tostring()
            p = self.pitch
        else:
            th = 255.0 * th
            r, g, b = img.split()
            if 0 == color:
                r = Image.eval(r, lambda i: 255 if i < th else 0)
                g = Image.eval(g, lambda i: 255 if i > th else 0)
                b = Image.eval(b, lambda i: 255 if i > th else 0)
            elif 1 == color:
                r = Image.eval(r, lambda i: 255 if i > th else 0)
                g = Image.eval(g, lambda i: 255 if i < th else 0)
                b = Image.eval(b, lambda i: 255 if i > th else 0)
            else:
                r = Image.eval(r, lambda i: 255 if i > th else 0)
                g = Image.eval(g, lambda i: 255 if i > th else 0)
                b = Image.eval(b, lambda i: 255 if i < th else 0)

            m = img.mode
            i = Image.merge(m, (r, g, b))
            d = i.tostring()
            p = -1 * w * len(m)
        return pyglet.image.ImageData(w, h, m, d, p)
Ejemplo n.º 26
0
 def takeSnapshot(self, *args):
     """taco"""
     if canTakeSnapshots:
         rawimg = self.device.DevCcdRead(1)
         try:
             img = Image.frombuffer(
                 "RGB", (self.getWidth(), self.getHeight()), rawimg
             )
             pixmap = img.tostring("raw", "BGR")
             img = Image.frombuffer("RGB", img.size, pixmap)
             # img.save(*args)
         except BaseException:
             logging.getLogger("HWR").exception(
                 "%s: could not save snapshot", self.name()
             )
         else:
             if len(args):
                 try:
                     img.save(*args)
                 except BaseException:
                     logging.getLogger("HWR").exception(
                         "%s: could not save snapshot", self.name()
                     )
                 else:
                     return True
             else:
                 return img
     else:
         logging.getLogger("HWR").error(
             "%s: could not take snapshot: sorry PIL is not available :-(",
             self.name(),
         )
     return False
Ejemplo n.º 27
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])
Ejemplo n.º 28
0
 def __call__(self, file_name):
     file_path = download_image_to_cache(file_name, self.cache)
     im = Image.open(file_path)
     if im.mode != self.mode:
         im = im.convert(self.mode)
     if np.all(im.size != self.resize_to):
         new_shape = (int(self.resize_to[0]), int(self.resize_to[1]))
         im = im.resize(new_shape, Image.ANTIALIAS)
     if self.mask is not None:
         mask = self.mask
         tmask = ImageOps.invert(mask.convert('RGBA').split()[-1])
         im = Image.composite(im, mask, tmask).convert(self.mode)
     if self._crop != (0, 0,) + self.resize_to:
         im = im.crop(self._crop)
     l, t, r, b = self._crop
     assert im.size == (r - l, b - t)
     imval = np.asarray(im, self.dtype)
     rval = imval
     if self.normalize:
         rval -= rval.mean()
         rval /= max(rval.std(), 1e-3)
     else:
         rval /= 255.0
     assert rval.shape[:2] == self.resize_to
     return rval
Ejemplo n.º 29
0
Archivo: image.py Proyecto: LCROBOT/rce
 def decode(self, _, imgObj):
     """ Convert a image stored (PIL library readable image file format)
         in a StringIO object to a ROS compatible message
         (sensor_msgs.Image).
     """
     if not _checkIsStringIO(imgObj):
         raise TypeError('Given object is not a StringIO instance.')
     
     # Checking of image according to django.forms.fields.ImageField
     try:
         imgObj.seek(0)
         img = Image.open(imgObj)
         img.verify()
     except:
         raise ValueError('Content of given image could not be verified.')
     
     imgObj.seek(0)
     img = Image.open(imgObj)
     img.load()
     
     # Everything ok, convert PIL.Image to ROS and return it
     if img.mode == 'P':
         img = img.convert('RGB')
     
     rosimage = sensor_msgs.msg.Image()
     rosimage.encoding = ImageConverter._ENCODINGMAP_PY_TO_ROS[img.mode]
     (rosimage.width, rosimage.height) = img.size
     rosimage.step = (ImageConverter._PIL_MODE_CHANNELS[img.mode]
                      * rosimage.width)
     rosimage.data = img.tostring()
     return rosimage
Ejemplo n.º 30
0
    def test_r(self):
        """ Line of circles (varying r) across image each produces a strong response """

        im = Image.new("L", (1000, 200), (0))
        npoints = 18
        xs = [ (100 + 50 * t) for t in range(npoints) ]
        for t in range(npoints):
            r = (2.0+0.5*t)
            circle(im, xs[t], 100, r, 248)

        # Add noise into the image.  If the image does not contain noise,
        # then the non maximum suppression can - like Buridan's ass - be
        # presented with two adjacent responses that are equal, and reject
        # both because neither is a maximum.  The chance of this happening
        # with real-world images is very remote indeed.

        noise = Image.fromstring("L", (1000,200), "".join([ chr(random.randrange(0, 8)) for i in range(1000 * 200)]))
        im = ImageChops.add(im, noise)

        result = sorted([(x,y,s,response) for (x,y,s,response) in simple(im, 7, 1.0, 999999.0, 999999.0)][-npoints:])

        # Must have npoints
        self.assertEqual(len(result), npoints)

        # X coordinates must be within 1 point of expected
        for i,(x,y,s,r) in enumerate(result):
            self.assert_(abs(x - xs[i]) <= 1)

        # Already ordered by x, so scale should be increasing
        ss = [s for (x,y,s,r) in result]
        self.assertEqual(ss, sorted(ss))
Ejemplo n.º 31
0
 def start(self):
   black = Image.new("RGBA", (self.width, self.height), 'black')
   im = Image.new("RGBA", (self.width, self.height), 'white')
   im.putalpha(black.split()[1])  # Make the alpha layer transparent, too.
   d = aggdraw.Draw(im)
   return (im, d)  
Ejemplo n.º 32
0
def bits_to_image(bits, height=50):
    rawbits = "".join([{'0': '\377', '1': '\0'}[c] for c in bits])
    im = Image.fromstring('L', (len(bits), 1), rawbits)
    return im.resize((len(bits), height)).convert('1')
Ejemplo n.º 33
0
import sys, os
import math
import string
import Image
import PIL.ImageChops

if __name__ == "__main__":
    input = sys.argv[1]
    base = Image.open(input).convert('L')

    class Fit:
        letter = None
        difference = 0

    best = Fit()

    for letter in string.lowercase:
        current = Fit()
        current.letter = letter

        sample_path = os.path.join('samples', letter + '.png')
        sample = Image.open(sample_path).convert('L').resize(base.size)
        difference = PIL.ImageChops.difference(base, sample)

        for x in range(difference.size[0]):
            for y in range(difference.size[1]):
                current.difference += difference.getpixel((x, y))

        print current.letter, current.difference
        if not best.letter or best.difference > current.difference:
            best = current
Ejemplo n.º 34
0
import numpy as np
from skimage import data
import ImagePlotter
import Image
import matplotlib.pyplot as plt
import PolygonCreator
import matplotlib.artist as artst
from matplotlib.patches import Polygon

im = Image.Image(np.ma.masked_array(data.camera()), calibration=3)
im.SaveImgAsPNG(
    '/home/isobel/Documents/McMaster/PythonCodes/DataAnalysis/Image_camera.png',
    [0, 255],
    cmap=plt.get_cmap('RdBu'))

fig = plt.figure()
ax = plt.axes([0, 0, 1, 1])
implot = ImagePlotter.ImagePlotter(im, ax, cmap=plt.get_cmap('RdBu'))
#creator = PolygonCreator.PolygonCreator(ax)

plt.show()
#im.SaveImgAsPNG('/home/isobel/Documents/McMaster/PythonCodes/DataAnalysis/testIm.png', im.Imglim)
#im2 = Image.Image(im.data*implot.mask)
#fig2 = plt.figure()
#ax2 = plt.axes([0,0,1,1])
#implot2 = ImagePlotter.ImagePlotter(im2, ax2)
#plt.show()
Ejemplo n.º 35
0
import Image
import ImageFont
import ImageDraw

disp = SSD1306.SSD1306_128_64()

disp.begin()

width = disp.width
height = disp.height

disp.clear()
disp.display()

image = Image.new('1', (width, height))
font = ImageFont.load_default()

# Some nice fonts to try: http://www.dafont.com/bitmap.php
# font = ImageFont.truetype('Minecraftia.ttf', 8)

# Create drawing object.
draw = ImageDraw.Draw(image)

text= "Intel Edison is the best thing since sliced bread!"
maxwidth, unused = draw.textsize(text, font=font)

# Set animation and sine wave parameters.
amplitude = height/4
offset = height/2 - 4
velocity = -3
Ejemplo n.º 36
0
# PIL Image module (create or load images) is explained here:
# http://effbot.org/imagingbook/image.htm
# PIL ImageDraw module (draw shapes to images) explained here:
# http://effbot.org/imagingbook/imagedraw.htm
 
import Image
import ImageDraw
import time
from rgbmatrix import Adafruit_RGBmatrix
 
# Rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(32, 3)
matrix.SetWriteCycles(5)
 
# Bitmap example w/graphics prims
image = Image.new("1", (64 * 10, 32)) # Can be larger than matrix if wanted!!
draw  = ImageDraw.Draw(image)    # Declare Draw instance before prims
# Draw some shapes into image (no immediate effect on matrix)...

def drawByCoords(coords, colour):
        for index, coord in enumerate(coords): 
                if index == (len(coords) - 1):
                        draw.line((coords[0], coords[index]), fill=colour)
                else:
                        draw.line((coords[index], coords[index + 1]), fill=colour)

def drawA(minX, minY, maxY, width, height, colour):
        maxX = minX + width
        coords = [
                (minX, minY),
                (minX, maxY),
Ejemplo n.º 37
0
def data_to_image(data):
    img = Image.fromstring('RGB',
                           (data.description.width, data.description.height),
                           data.pixelData, 'raw', "BGR")
    pix = numpy.array(img)
    return pix
Ejemplo n.º 38
0
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
# file: 16.py
# date: 2012-10-11 author: kyon

import Image


def straighten(line):
    idx = 0
    while line[idx] != 195:
        idx += 1
    return line[idx:] + line[:idx]


im = Image.open('mozart.gif')
for y in range(im.size[1]):
    line = [im.getpixel((x, y)) for x in range(im.size[0])]
    line = straighten(line)
    [im.putpixel((x, y), line[x]) for x in range(len(line))]

im.show()
Ejemplo n.º 39
0
def image_preview(request, app_label, model, id,  size):
    """
        Grab all image link within a peice of content
        and generate thumbnails of largest image
    """
    # get page object; protect size
    try:
        content_type = ContentType.objects.get(app_label=app_label, model=model)
        instance = content_type.get_object_for_this_type(id=id)
    except:
        return HttpResponseNotFound("Image not found.", mimetype="text/plain")
    
    keys = [settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model, str(instance.id), size]
    key = '.'.join(keys)
    response = cache.get(key)
    original_size = size
    
    if not response:
        from tendenci.core.base.utils import parse_image_sources, make_image_object_from_url, image_rescale

        # set sizes
        size_min = (30,30)
        size_cap = (512,512)
        
        size_tuple = size.split('x')
        if len(size_tuple) == 2: size = int(size_tuple[0]), int(size_tuple[1])
        else: size = int(size), int(size)

        if size > size_cap: size = size_cap

        image_urls = []

        image = Pil.new('RGBA',size_min)
    
        # find biggest image, dimension-wise
        for image_url in image_urls:
            image_candidate = make_image_object_from_url(image_url)
            if image_candidate:
                if image_candidate.size > image.size:
                    image = image_candidate

        if image.size[1] > size_min[1]:
        # rescale, convert-to true-colors; return response
    
            image = image_rescale(image, size)
            if image.mode != "RGB":
                image = image.convert("RGB")
    
            response = HttpResponse(mimetype='image/jpeg')
            
            image.save(response, "JPEG", quality=100)
            
            keys = [settings.CACHE_PRE_KEY, IMAGE_PREVIEW_CACHE, model, str(instance.id), size]
            key = '.'.join(keys)
            
            cache.set(key, response)
            return response
    
        else: # raise http 404 error (returns page not found)
            return HttpResponseNotFound("Image not found.", mimetype="text/plain")
    else:
        return response
Ejemplo n.º 40
0
def cv2pil(cv_im):
    return Image.fromstring(cv.GetSize(cv_im), "L", cv_im.tostring())
Ejemplo n.º 41
0
TEXT_TITLE =   str(sys.argv[1])
TEXT_MSG   =   str(sys.argv[2])

disp = TFT.ILI9341(24, rst=25, spi=SPI.SpiDev(0,0,max_speed_hz=64000000))
disp.begin()
disp.clear()

image = disp.buffer
fill = (255,255,255)
angle = 90

font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 30)
draw = ImageDraw.Draw(image)
t_width, t_height = draw.textsize(TEXT_TITLE, font=font)
textimage = Image.new('RGBA', (t_width, t_height), (0,0,0,0))
textdraw = ImageDraw.Draw(textimage)
textdraw.text((0,0), TEXT_TITLE, font=font, fill=fill)
rotated = textimage.rotate(angle, expand=1)
x_pos = 280
y_pos = 80
position = (y_pos,x_pos-t_width)
image.paste(rotated, position, rotated)

font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 20)
draw = ImageDraw.Draw(image)
t_width, t_height = draw.textsize(TEXT_MSG, font=font)
textimage = Image.new('RGBA', (t_width, t_height), (0,0,0,0))
textdraw = ImageDraw.Draw(textimage)
textdraw.text((0,0), TEXT_MSG, font=font, fill=fill)
rotated = textimage.rotate(angle, expand=1)
Ejemplo n.º 42
0
 def draw_all(self):
   if 1:
     (im, d) = self.start()
     d.rectangle((self.left, self.top, self.right, self.bottom), None, self.white_brush)
     d.rectangle((self.left, self.top, self.right, self.bottom), self.black_pen)
     self.finish(im, d, 'male')
 
   if 1:
     (im, d) = self.start()
     d.rectangle((self.left - 3, self.top - 3, self.right + 3, self.bottom + 3), self.highlight_pen)
     self.finish(im, d, 'male-selected')
 
   if 1:
     (im, d) = self.start()
     d.rectangle((self.left, self.top, self.right, self.bottom), None, self.affected_brush)
     d.rectangle((self.left, self.top, self.right, self.bottom), self.black_pen)
     self.finish(im, d, 'male-aff')
 
   if 1:
     (im, d) = self.start()
     d.ellipse((self.left, self.top, self.right, self.bottom), None, self.white_brush)
     d.ellipse((self.left, self.top, self.right, self.bottom), self.black_pen)
     self.finish(im, d, 'female')
 
   if 1:
     (im, d) = self.start()
     d.ellipse((self.left - 3, self.top - 3, self.right + 3, self.bottom + 3), self.highlight_pen)
     self.finish(im, d, 'female-selected')
 
   if 1:
     (im, d) = self.start()
     d.ellipse((self.left, self.top, self.right, self.bottom), None, self.affected_brush)
     d.ellipse((self.left, self.top, self.right, self.bottom), self.black_pen)
     self.finish(im, d, 'female-aff')
 
   if 1:
     (im, d) = self.start()
     inset = unit * 2 / 5
     self.left2 = self.margin + inset + 0.5
     self.top2 = self.margin + inset + 0.5
     self.right2 = unit + self.margin - inset + 0.5
     self.bottom2 = unit + self.margin - inset + 0.5
     d.ellipse((self.left2, self.top2, self.right2, self.bottom2), None, self.black_brush)
     d.ellipse((self.left2, self.top2, self.right2, self.bottom2), self.black_pen)
     self.finish(im, d, 'carrier-dot')
 
   if 1:
     (im, d) = self.start()
 
     a = unit / 2   # arrow line length
     b = unit / 4   # arrow end length
     dd = unit / 10  # distance of arrow from unit box
 
     x0 = self.left - a
     y0 = self.bottom + a
     x1 = self.left - dd
     y1 = self.bottom + dd
     x2 = x1 - b
     y2 = y1
     x3 = x1
     y3 = y1 + b
     d.line((x0, y0, x1, y1), self.thick_black_pen)
     d.line((x1, y1, x2, y2), self.thick_black_pen)
     d.line((x1, y1, x3, y3), self.thick_black_pen)
     self.finish(im, d, 'proband-arrow')
 
   if 1:
     x0 = self.left + unit / 2
     y0 = self.top
     x1 = self.right
     y1 = self.top + unit / 2
     x2 = self.left + unit / 2
     y2 = self.bottom
     x3 = self.left
     y3 = self.top + unit / 2
     (im, d) = self.start()
     d.polygon((x0, y0, x1, y1, x2, y2, x3, y3), self.black_pen, self.white_brush)
     self.finish(im, d, 'nogender')
 
     (im, d) = self.start()
     d.polygon((x0, y0 - 4, x1 + 4, y1, x2, y2 + 4, x3 - 4, y3),
               self.highlight_pen)
     self.finish(im, d, 'nogender-selected')
 
     (im, d) = self.start()
     d.polygon((x0, y0, x1, y1, x2, y2, x3, y3), None, self.affected_brush)
     d.polygon((x0, y0, x1, y1, x2, y2, x3, y3), self.black_pen)
     self.finish(im, d, 'nogender-aff')
 
   if 1:
     x0 = self.left + unit / 2
     y0 = self.top
     x1 = self.right
     y1 = self.top + unit / 2
     x2 = self.left
     y2 = self.top + unit / 2
     (im, d) = self.start()
     d.polygon((x0, y0, x1, y1, x2, y2), self.black_pen, self.white_brush)
     self.finish(im, d, 'pregloss')
 
     (im, d) = self.start()
     d.polygon((x0, y0 - 4, x1 + 4, y1 + 4, x2 - 4, y2 + 4),
               self.highlight_pen)
     self.finish(im, d, 'pregloss-selected')
 
     (im, d) = self.start()
     d.polygon((x0, y0, x1, y1, x2, y2), None, self.affected_brush)
     d.polygon((x0, y0, x1, y1, x2, y2), self.black_pen)
     self.finish(im, d, 'pregloss-aff')
 
   if 1:
     (im, d) = self.start()
     x0 = self.right + unit / 8
     y0 = self.top - unit / 8
     x1 = self.left - unit / 8
     y1 = self.bottom + unit / 8
     d.line((x0, y0, x1, y1), self.black_pen)
     self.finish(im, d, 'dead-slash')
 
   if 1:
     (im, d) = self.start()
     x0 = self.width / 2
     y0 = unit / 4
     x1 = self.width - unit / 4
     y1 = self.height - unit / 4
     d.arc((x0, y0, x1, y1), 270, 90, self.highlight_pen)
     self.finish(im, d, 'rowmarker-selected')
 
   if 0:
     im = Image.new("RGBA", (128, 128), None)
     d = aggdraw.Draw(im)
     p = aggdraw.Pen("red", 5, opacity=127)
     b = aggdraw.Brush("yellow", opacity=127)
     d.line((0, 0, 128, 128), p)
     d.line((0, 128, 128, 0), p)
     d.arc((48, 48, 96, 96), 0, 315, p)
     d.pieslice((48, 48, 96, 96), 0, 315, None, b)
     d.polygon((16, 16, 48, 16, 48, 48, 16, 16), None, b)
     d.flush()
     im.save('out.tiff')
     os.system('convert out.tiff out.png')
Ejemplo n.º 43
0
print 'Converting %s' % fn

import Image, ImageDraw, os
from struct import unpack

f = open(fn, 'rb')

FRAME_ANIM = 7
FRAME_SINGLE = 3

_, frame_width, frame_height, frame_type, frame_count = \
    unpack('IIIII', f.read(4*5))

img_size = frame_width * frame_height

img = Image.new('RGBA', (frame_width * frame_count, frame_height))


def parse565a(i, a):
    r = ((0xF800 & i) >> 11) << 3
    g = ((0x07E0 & i) >> 5) << 2
    b = ((0x001F & i) >> 0) << 3
    return (r, g, b, min(a << 3, 255))


def convert(imgdata, alpha, sz):
    #sz = len(alpha)
    imgdata = unpack('H' * sz, imgdata)
    alpha = unpack('B' * sz, alpha)
    pixels = [parse565a(i, a) for i, a in zip(imgdata, alpha)]
    return pixels
Ejemplo n.º 44
0
def get_image_format(base64_string):
    """returns image format from base64 encoded string"""

    image_stream = io.BytesIO((base64.b64decode(base64_string)))
    image = Image.open(image_stream)
    return image.format
Ejemplo n.º 45
0
def _get_gray_image(colored_image: Image) -> Image:
    """Converts colored image to gray image."""
    if colored_image is None:
        return None
    return colored_image.convert("L")
Ejemplo n.º 46
0
# PIL Image module (create or load images) is explained here:
# http://effbot.org/imagingbook/image.htm
# PIL ImageDraw module (draw shapes to images) explained here:
# http://effbot.org/imagingbook/imagedraw.htm

import Image
import ImageDraw
import time
from rgbmatrix import Adafruit_RGBmatrix

# Rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(32, 4)

# Bitmap example w/graphics prims
image = Image.new("1", (32, 32))  # Can be larger than matrix if wanted!!
draw = ImageDraw.Draw(image)  # Declare Draw instance before prims
# Draw some shapes into image (no immediate effect on matrix)...
draw.rectangle((0, 0, 31, 16), fill=0, outline=1)
# draw.line((0, 0, 31, 31), fill=1)
# draw.line((0, 31, 31, 0), fill=1)
# Then scroll image across matrix...
for n in range(-32, 97):  # Start off top-left, move off bottom-right
    matrix.Clear()
    # IMPORTANT: *MUST* pass image ID, *NOT* image object!
    matrix.SetImage(image.im.id, 2 * n, n)
    time.sleep(0.05)

# 8-bit paletted GIF scrolling example
image = Image.open("cloud.gif")
image.load()  # Must do this before SetImage() calls
Ejemplo n.º 47
0
#!/usr/bin/python
#coding:utf-8
import sys
import Image

for i in range(1, len(sys.argv)):
    try:
        im = Image.open(sys.argv[i])
        im = im.convert("RGB")
        im.save(sys.argv[i].split('.')[0] + ".jpg")
        print " %s change success." % sys.argv[i]
    except Exception, e:
        print e
        print " %s change failed." % sys.argv[i]
Ejemplo n.º 48
0
 def image(self, path_img):
     """ Open image file """
     im_open = Image.open(path_img)
     im = im_open.convert("RGB")
     # Convert the RGB image in printable image
     self._convert_image(im)
Ejemplo n.º 49
0
from itertools import izip
import Image

i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."

pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
    # for gray-scale jpegs
    dif = sum(abs(p1 - p2) for p1, p2 in pairs)
else:
    dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))

ncomponents = i1.size[0] * i1.size[1] * 3
print "Difference (percentage):", (dif / 255.0 * 100) / ncomponents
Ejemplo n.º 50
0
def _get_image_from_array(scale: int, array) -> Image:
    """Converts a scaled array into Image."""
    if scale is None or array is None:
        return None
    return Image.fromarray(_apply_scale(scale, array))
Ejemplo n.º 51
0
	def test01_create_new_image(self):
		for mode in MODES:
			image = Image.new(mode, (100, 100))
			self.assertNotEquals(None, image)
			self.images.append(image)
		self.assertNotEquals(0, len(self.images))
Ejemplo n.º 52
0
    def OnConvert(self, event):  # wxGlade: RootFrame.<event_handler>
        import PIL.ImageOps
        import Image
        import imghdr
        import shutil
        import glob
        import time
        import os
        import sys

        # get select options
        is_resize = self.checkbox_resize.IsChecked()  # type: bool
        if is_resize:
            resize_mode = self.resize_mode_radio_box.GetSelection(
            )  # type: int
            width = int(self.input_resize_width.GetValue())  # type: int
            if resize_mode == 0:
                height = int(self.input_resize_height.GetValue())  # type: int
            else:
                height = 1  # type: int
            is_aspect = self.checkbox_aspect.IsChecked()  # type: bool
            is_zoom = self.checkbox_zoom.IsChecked()  # type: bool
            resample_mode = self.resample_mode_radio_box.GetSelection(
            )  # type: int

        is_colors = self.checkbox_colors.IsChecked()  # type: bool
        if is_colors:
            color_mode = self.combo_box_colors.GetSelection()  # type: int

        is_flip_horizontal = self.checkbox_flip_holizontal.IsChecked(
        )  # type: bool
        is_flip_vertical = self.checkbox_flip_vertical.IsChecked(
        )  # type: bool
        is_flip_exif = self.checkbox_flip_exif.IsChecked()  # type: bool
        is_grayscale = self.checkbox_grayscale.IsChecked()  # type: bool
        is_flip_negative = self.checkbox_negative.IsChecked()  # type: bool
        is_remove_exif = self.checkbox_remove_exif.IsChecked()  # type: bool

        is_file_overwrite = self.checkbox_file_overwrite.IsChecked(
        )  # type: bool

        is_file_output_dir = self.checkbox_output_dir.IsChecked()  # type: bool
        if is_file_output_dir:
            file_output_dir = self.input_output_dir.GetValue()  # type: int

        is_file_format = self.checkbox_file_format.IsChecked()  # type: bool
        if is_file_format:
            file_format = self.combo_box_format.GetSelection()  # type: int

        save_quality = self.slider_save_quality.GetValue()  # type: int
        # end get select options

        # CONSTANT
        RESAMPLE_MODES = [Image.ANTIALIAS, Image.BICUBIC,
                          Image.BILINEAR]  # type: List[int]
        FORMATS = {
            0: ['JPEG', 'jpg'],
            1: ['PNG', 'png'],
            2: ['GIF', 'gif'],
        }  # type: Dict[int, List[str, str]]
        TMP_DIR = os.path.join('/tmp',
                               'pylfan-' + str(time.time()))  # type: str
        CONVERT_IMAGE = {
            1:
            lambda img: img,
            2:
            lambda img: img.transpose(Image.FLIP_LEFT_RIGHT),
            3:
            lambda img: img.transpose(Image.ROTATE_180),
            4:
            lambda img: img.transpose(Image.FLIP_TOP_BOTTOM),
            5:
            lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(
                Image.ROTATE_90),
            6:
            lambda img: img.transpose(Image.ROTATE_270),
            7:
            lambda img: img.transpose(Image.FLIP_LEFT_RIGHT).transpose(
                Image.ROTATE_270),
            8:
            lambda img: img.transpose(Image.ROTATE_90),
        }  # type: Dict[int: func]
        # end CONSTANT

        # INITIALIZE
        os.mkdir(TMP_DIR)
        # end INITIALIZE

        for convert_filename in self.convert_files:
            print convert_filename
            convert_file_path = os.path.join(self.convert_file_dir,
                                             convert_filename)  # type: str
            shutil.copy(convert_file_path, TMP_DIR)

            image = Image.open(os.path.join(TMP_DIR,
                                            convert_filename))  # type: Image
            image_type = imghdr.what(convert_file_path)  # type: str

            if image_type == 'jpeg' and 'exif' in image.info:
                exif_str = image.info['exif']  # type: str
            else:
                exif_str = ''  # type: str

            if image_type == 'jpeg' and is_flip_exif:
                exif = image._getexif()  # type: Dict[Blob: Any]
                if exif is not None:
                    orientation = exif.get(0x112, 1)  # type: int
                    image = CONVERT_IMAGE[orientation](image)  # type: Image

            if is_resize:
                if (width >= image.size[0]
                        and height >= image.size[1]) and not is_zoom:
                    pass
                else:
                    if resize_mode == 1 or resize_mode == 2:
                        height = width
                    w_percent = (width / float(image.size[0]))  # type: float
                    h_percent = (height / float(image.size[1]))  # type: float
                    w_new_size = int(
                        (float(image.size[0]) * float(h_percent)))  # type: int
                    h_new_size = int(
                        (float(image.size[1]) * float(w_percent)))  # type: int

                    # width and height or long side
                    if resize_mode == 0 or resize_mode == 1:
                        if is_aspect or resize_mode == 1:
                            if w_percent <= h_percent:
                                image = image.resize(
                                    (width, h_new_size),
                                    RESAMPLE_MODES[resample_mode]
                                )  # type: Image
                            else:
                                image = image.resize(
                                    (w_new_size, height),
                                    RESAMPLE_MODES[resample_mode]
                                )  # type: Image
                        else:
                            image = image.resize(
                                (height, width),
                                RESAMPLE_MODES[resample_mode])  # type: Image
                    # narrow side
                    elif resize_mode == 2:
                        if w_percent >= h_percent:
                            image = image.resize(
                                (width, h_new_size),
                                RESAMPLE_MODES[resample_mode])  # type: Image
                        else:
                            image = image.resize(
                                (w_new_size, width),
                                RESAMPLE_MODES[resample_mode])  # type: Image

            if is_colors:
                if color_mode == 0:
                    pass
                elif color_mode == 1:
                    image = image.point(
                        lambda point: int(point / 32) * 32)  # type: Image
                elif color_mode == 2:
                    image = image.point(
                        lambda point: int(point / 64) * 64)  # type: Image
                elif color_mode == 3:
                    image = image.convert('L').point(
                        lambda point: 0 if point < 127 else 255)  # type: Image

            if is_flip_horizontal:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)  # type: Image

            if is_flip_vertical:
                image = image.transpose(Image.FLIP_TOP_BOTTOM)  # type: Image

            if is_grayscale:
                image = image.convert('L')  # type: Image

            if is_flip_negative:
                image = image.point(lambda point: 255 - point)  # type: Image

            if is_remove_exif:
                exif_str = ''  # type: str

            save_options = {
                'quality': save_quality,
            }  # type: Dict[str, Any]

            if image_type == 'jpeg':
                save_options['exif'] = exif_str  # type: str

            if is_file_format:
                new_format = FORMATS[file_format][1]  # type: str
                if new_format != 'jpg':
                    del save_options['exif']

                new_filename = '{0}.{1}'.format('.'.join(
                    convert_filename.split('.')[:-1]), new_format)  # type: str
                image.save(os.path.join(TMP_DIR, new_filename),
                           FORMATS[file_format][0], **save_options)
                if new_filename != convert_filename:
                    os.remove(os.path.join(TMP_DIR, convert_filename))
            else:
                image.save(os.path.join(TMP_DIR, convert_filename),
                           **save_options)

        if is_file_output_dir:
            move_dir = os.path.join(self.convert_file_dir,
                                    file_output_dir)  # type: str
            if not os.path.exists(move_dir):
                os.mkdir(move_dir)
        elif is_file_overwrite:
            move_dir = file_output_dir
        else:
            print 'make file an {0} directory'.format(TMP_DIR)
            sys.exit()

        for file_path in glob.glob(os.path.join(TMP_DIR, '*')):
            shutil.copy(file_path, move_dir)
Ejemplo n.º 53
0
import sys
import Image
import math

im = Image.open( sys.argv[1] )

colors = set()
pixels = im.load()

for x in range( im.size[0] ):
    for y in range( im.size[1] ):
        col = pixels[x,y]
        colors.add( col )

def diff( col, r, g, b ):
    r = col[0] - ( r * 16 )
    g = col[1] - ( g * 16 )
    b = col[2] - ( b * 16 )

    return math.sqrt( r * r + g * g + b * b )

out = Image.new( "RGB", ( 64, 64 ), "white" )

def mapping( r, g, b ):
    i = r + ( g * 16 ) + ( b * 16 * 16 )

    ret = ( int( i / 64 ), i % 64 )
    print( i )
    return ret

Ejemplo n.º 54
0
# print B1
# print B1[1]
# print B2.tolist()
# B1 = [ 0.48474296547776,0.551969023948957,0.558567032354462, 1.50100351629426]
# B2 = [0.537557976096806, 0.64004051936919,0.688031083731422,0.656995808363111]
B_max = max2(max2d(B1), max2d(B2))
B1 = divit(B1, B_max)
B2 = divit(B2, B_max)
# B1=newList = [x / B_max for x in B1]
# B2=newList = [x / B_max for x in B2]
# print B1
x = 1024 / 2
y = 1024 / 2
print B1
th = x / len(B1[0])
img1 = Image.new('RGB', (x, y), "black")  # create a new black image
pixels = img1.load()  # create the pixel map

for i in range(img1.size[0]):  # for every pixel:
    for j in range(img1.size[1]):
        # pixels[i,j] = (i, i,j) # set the colour accordingly
        val = int(B2[i / th][j / th] * 255.0)
        pixels[i, j] = (val, 0, 0)
        # print pixels[i,j]

img1.show()

img2 = Image.new('RGB', (x, y), "black")  # create a new black image
pixels = img2.load()  # create the pixel map

for i in range(img2.size[0]):  # for every pixel:
Ejemplo n.º 55
0
    norm_image = np.float32(original_image - minval) * ( 255 / (maxval - minval))
    norm_image[norm_image < 0] = 0
    norm_image[norm_image > 255] = 255
    return norm_image / 255.0

_, model_path, img_in, img_out = sys.argv[0:4]

# For lib_maxout_theano_batch we can control batch size
# batch_size = 1024
# if len(sys.argv) > 4:
#     batch_size = int(sys.argv[4])
# network = DeepNetwork(model_path, batch_size=batch_size)

network = DeepNetwork(model_path)

input_image = normalize_image_float(np.array(Image.open(img_in)))
nx, ny = input_image.shape

pad_by = network.pad_by
pad_image = np.pad(input_image, ((pad_by, pad_by), (pad_by, pad_by)), 'symmetric')

start_time = time.time()

output = network.apply_net(pad_image, perform_pad=False)

print 'Complete in {0:1.4f} seconds'.format(time.time() - start_time)

im = Image.fromarray(np.uint8(output * 255))
im.save(img_out)

print "Image saved."
Ejemplo n.º 56
0
def thumbnail(url, size='200x200'):
    """
    Given a URL (local or remote) to an image, creates a thumbnailed version of the image, saving
    it locally and then returning the URL to the new, smaller version. If the argument passed is a
    single integer, like "200", will output a version of the image no larger than 200px wide. If the
    argument passed is two integers, like, "200x300", will output a cropped version of the image that
    is exactly 200px wide by 300px tall.

    Examples:

    {{ story.leadphoto.url|thumbnail:"200" }}
    {{ story.leadphoto.url|thumbnail:"300x150" }}

    """
    import Image
    import os
    import urllib

    original_url = url

    # First, find the image, either via local file path or http.
    filename = os.path.join(settings.MEDIA_ROOT, url)

    if url.startswith('http://') or url.startswith('https://'):
        # If it's a remote image, download it and save it locally. This expects a
        # directory called downloaded/ in your MEDIA_ROOT
        download_filename = url.rsplit('/', 1)[1]  # Filename of image
        full_image_path = '%sdownloaded/%s' % (
            settings.MEDIA_ROOT, download_filename
        )  # Local filesystem path where image should be saved
        local_image_url = '%sdownloaded/%s' % (
            settings.MEDIA_URL, download_filename
        )  # URL to local copy of image

        if not os.path.exists(full_image_path):
            unsized_image = urllib.urlretrieve(url)  # Fetch original image
            unsized_image = Image.open(
                unsized_image[0])  # Load the fetched image
            local_image = unsized_image.save(
                full_image_path)  # Save the resized image locally

        url = local_image_url
        remote_image = True
    else:
        # If it's a local image, note it and move on.
        remote_image = False

    # Define the thumbnail's filename, file path, and URL.
    try:
        basename, format = url.rsplit('.', 1)
    except ValueError:
        return os.path.join(settings.MEDIA_URL, url)
    thumbnail = basename + '_t' + size + '.' + format
    thumbnail_filename = _get_path_from_url(thumbnail)
    thumbnail_url = thumbnail

    # Find out if a thumbnail in this size already exists. If so, we'll not remake it.
    if not os.path.exists(thumbnail_filename):
        # The thumbnail doesn't already exist. Log a message that we are resizing.

        # Open the image.
        try:
            image = Image.open(_get_path_from_url(url))
        except IOError:
            return os.path.join(settings.MEDIA_URL, url)

        # Make a copy of the original image so we can access its attributes, even
        # after we've changed some of them.
        original_image = image.copy()

        # Find the size of the original image.
        original_width = original_image.size[0]
        original_height = original_image.size[1]

        # Parse the size argument into integers.
        try:
            # See if both height and width exist (i.e. "200x100")
            desired_width, desired_height = [int(x) for x in size.split('x')]
            new_size = (desired_width, desired_height)
            # Flag this image for cropping, since we want an explicit width AND height.
            crop = True
        except ValueError:
            # If only one exists ( i.e. "200"), use the value as the desired width.
            if size[0] == 'x':
                desired_height = int(size[1:])
                new_size = (original_width, desired_height)
                crop = False
            else:
                desired_width = int(size)
                new_size = (desired_width, original_height)
                crop = False

        # If we are to crop this image, we'll thumbnail it, and then figure out the proper crop area
        # Crops are done from the center of the image.
        if crop:
            if (original_height /
                (original_width / float(desired_width))) < desired_height:
                image.thumbnail((original_width, desired_height),
                                Image.ANTIALIAS)
            else:
                image.thumbnail((desired_width, original_height),
                                Image.ANTIALIAS)

            if (image.size[0] >= desired_width) and (image.size[1] >=
                                                     desired_height):
                left = (image.size[0] - desired_width) / 2
                top = (image.size[1] - desired_height) / 2
                right = left + desired_width
                bottom = top + desired_height
                cropped_image = image.crop((left, top, right, bottom))
                image = cropped_image
        else:
            # If we are not to crop this image, simply thumbnail it down to the desired width.
            image.thumbnail(new_size, Image.ANTIALIAS)

        # Finally, save the image.
        try:
            image.save(thumbnail_filename, image.format, quality=85)
        except KeyError:
            return ''

    # And return the URL to the new thumbnailed version.
    return os.path.join(settings.MEDIA_URL, thumbnail_url)
    if os.path.isfile(fname):
        newfile = fname + '.old'
        print('{0} -> {1}'.format(fname, newfile))
        os.rename(fname, newfile)


with mss.mss() as sct:
    #filename = sct.shot(output='mon-{mon}.png', callback=on_exists)
    #print(filename)
    #import mss
    # -249, 1285
    import mss.tools

    with mss.mss() as sct:
        monitor = {'top': 1268, 'left': -324, 'width': 133, 'height': 33}
        output = 'sct-{top}x{left}_{width}x{height}.png'.format(**monitor)

        # Grab the data
        sct_img = sct.grab(monitor)

        # Save to the picture file
        mss.tools.to_png(sct_img.rgb, sct_img.size, output)
        time.sleep(3)
        #print (os.path.join("D:", "revolution_macro", "healthcheck", output))
        #print(pytesseract.image_to_string(Image.open(os.path.join("D:", "revolution_macro", "healthcheck", output))))
        tessdata_dir_config = '--tessdata-dir "D:\\revolution_macro\\healthcheck"'
        print(
            pytesseract.image_to_string(Image.open('sct-1268x-324_133x33.png'),
                                        lang='kor',
                                        config=tessdata_dir_config))
Ejemplo n.º 58
0
import Image, ImageDraw, ImageFont
import os, sys, random
import math


def lerp(a, b, t):
    return a * t + b * (1. - t)


def inBound(point, bound):
    return point[0] in xrange(bound[0]) and point[1] in xrange(bound[1])


im = Image.new('L', (210, 80), 255)

draw = ImageDraw.Draw(im)
fonts = [
    ImageFont.truetype("Kinnari-Italic.ttf", 45 + i * 3) for i in xrange(5)
]
chars = list('svRtUh84')
random.shuffle(chars)
curr_x = 30
for char in chars:
    font_number = random.randint(0, 4)
    draw.text((curr_x, -10), char, font=fonts[font_number])
    curr_x += draw.textsize(char, font=fonts[font_number])[0] - random.randint(
        7, 9)

for i in xrange(random.randint(7, 11)):
    noise_point = (random.randint(10, im.size[0] - 10),
                   random.randint(10, im.size[1] - 10))
Ejemplo n.º 59
0
#!/usr/bin/env python
from pylab import *
try:
    import Image
except ImportError, exc:
    raise SystemExit("PIL must be installed to run this example")

lena = Image.open('../data/lena.jpg')
dpi = rcParams['figure.dpi']
figsize = lena.size[0] / dpi, lena.size[1] / dpi

figure(figsize=figsize)
ax = axes([0, 0, 1, 1], frameon=False)
ax.set_axis_off()
im = imshow(lena, origin='lower')

show()
Ejemplo n.º 60
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Date    : 2016-05-23 16:14:22
# @Author  : Yunyu2019 ([email protected])
# @Link    : www.pythonchallenge.com/pc/ring/bell.html

import Image
img=Image.open('bell.png')
img.load()
r,g,b=img.split()
data=list(g.getdata())
l=zip(data[::2],data[1::2])
l1=[abs(odd-even) for odd,even in l if abs(odd-even)!=42]
s=''.join(map(chr,l1))
print s #whodunnit().split()[0] ?
"""
whodunnit().split()[0] ? 读出来hudownit==>Guido van Rossum==>guido
"""