Exemplo n.º 1
0
def symbols_in(image):
	symbols = []
	
	cut = []
	
	pixels = 0
	
	for i in range(image.size[0]):
		whitespace = True
		for j in range(image.size[1]):
			if image.getpixel((i, j)) != (255, 255, 255):
				whitespace = False
				break
		
		if whitespace:
			if pixels > 0:
				cut = cut + [i]
				pixels = 0
		else:
			pixels = pixels + 1
	
	if pixels > 0:
		cut = cut + [i]
		pixels = 0
		
	x = 0
	
	for i in range(len(cut)):
		image = ImageOps.invert(image)
		crop = image.crop([x, 0, cut[i], image.size[1]])
		image = ImageOps.invert(image)
		x = cut[i]
		symbols = symbols + [ImageOps.invert(crop)]
		
	return symbols
Exemplo n.º 2
0
def draw_mask(angle,width,height,offset_init,offset_A,offset_focus,offset_B):
	offset = height*offset_init/100
	vectorA = offset+offset_A*height/100
	focus = vectorA+offset_focus*height/100
	vectorB = focus+offset_B*height/100

	mask = Image.new('L', (width,height))
	mask_1px = Image.new('L', (1,height))
	draw_1px = ImageDraw.Draw(mask_1px)
	for y in range (0,offset): # draw white zone
		draw_1px.point((0,y),255)
	for y in range (offset,vectorA): # draw vectorA
		draw_1px.point((0,y),(vectorA-y)*(255/(vectorA-offset)))
	for y in range (vectorA,focus):	# draw white zone
		draw_1px.point((0,y),0)
	for y in range (focus,vectorB):	# draw vectorB
		draw_1px.point((0,y),255-(vectorB-y)*(255/(vectorB-focus)))
	for y in range (vectorB,height): # draw white zone
		draw_1px.point((0,y),255)
	
	m_width,m_height = mask.size
	mask_1px = mask_1px.resize((int(m_width*3),m_height), Image.ANTIALIAS)
	mask_1px = ImageOps.invert(mask_1px)
	mask_top = mask_1px.rotate(angle,Image.NEAREST,1)
	mask_top = ImageOps.invert(mask_top)

	mask.convert("RGBA")
	n_width,n_height = mask_top.size
	mask.paste(mask_top,(-n_width/2,-(n_height/2-height/2)))
	mask.convert("L")
	return mask
Exemplo n.º 3
0
    def process(self, _edObject=None):
        """
        This is the main method of the plugin, it does the job, not the EDNA name conversions which were done in the preprocess. 
        """

        EDPluginExec.process(self)
        EDVerbose.DEBUG("EDPluginPyarchThumbnailv10.process")
        if self.inputFilename:
            #        Read the image using FABIO
            fabioImage = openimage(self.inputFilename)
            # Convert an FabioImage to a PIL image
            npaImageRaw = fabioImage.data

            iMinLevel = 2
            iMaxLevel = 1000
            npaImageRaw = numpy.minimum(npaImageRaw, iMaxLevel * numpy.ones_like(npaImageRaw))
            npaImageRaw = numpy.maximum(npaImageRaw, iMinLevel * numpy.ones_like(npaImageRaw))

            npaImage = scipy.ndimage.morphology.grey_dilation(npaImageRaw, size=(5, 5))
            npaImageThumb = scipy.ndimage.morphology.grey_dilation(npaImageRaw, size=(10, 10))

            dtype = str(npaImage.dtype)
            if dtype == "uint8":
                NPAImageFloat = npaImage.astype("float") / 255.0
                NPAImageFloatThumb = npaImageThumb.astype("float") / 255.0
            elif dtype == "uint16":
                NPAImageFloat = npaImage.astype("float") / 65535.0
                NPAImageFloatThumb = npaImageThumb.astype("float") / 65535.0
            else: #for float or whatever
                vmin = npaImage.min()
                vmax = npaImage.max()
                NPAImageFloat = (npaImage.astype(float) - vmin) / (vmax - vmin)
                vminThumb = npaImageThumb.min()
                vmaxThumb = npaImageThumb.max()
                NPAImageFloatThumb = (npaImageThumb.astype(float) - vminThumb) / (vmax - vminThumb)

            NPAImageInt = (255.0 * (NPAImageFloat ** 0.3)).astype("uint8")
            NPAImageIntThumb = (255.0 * (NPAImageFloatThumb ** 0.3)).astype("uint8")

            pilImage = Image.fromarray(NPAImageInt, 'L')
            pilImageThumb = Image.fromarray(NPAImageIntThumb, 'L')
            # For ISPyB we use for the moment only 1024x1024 and 256x256
            pilImage.thumbnail((1024, 1024), Image.ANTIALIAS)
            pilImageThumb.thumbnail((256, 256), Image.ANTIALIAS)

            pilImage = ImageOps.invert(pilImage)
            pilImageThumb = ImageOps.invert(pilImageThumb)

            self.synchronizeOn()
            if 1024 * 1024 > ImageFile.MAXBLOCK:
                ImageFile.MAXBLOCK = 1024 * 1024


            pilImage.save(self.strOutputPath, "JPEG", quality=50, optimize=True)
            pilImageThumb.save(self.strOutputPathThumb, "JPEG", quality=85, optimize=True)

            self.synchronizeOff()
Exemplo n.º 4
0
	def threshold(img, thresh):
		"""Threshold an image"""
		
		pilIMG1 = Image.fromarray(img);
		pilInverted1 = ImageOps.invert(pilIMG1);
		inverted = numpy.asarray(pilInverted1);
		r, t = cv2.threshold(inverted, thresh, 0, type=cv.CV_THRESH_TOZERO);
		pilIMG2 = Image.fromarray(t);
		pilInverted2 = ImageOps.invert(pilIMG2);
		thresholded = numpy.asarray(pilInverted2);
		return thresholded;
Exemplo n.º 5
0
    def _derotationTest(self, imageName):
        image = samples.getSample("algorithmTests", imageName)[0]
        inverted = ImageOps.invert(image.convert("L"))
        before = derotate._getAngle(inverted)

        derotated = derotate.derotate(image)
        invertedDerotated = ImageOps.invert(derotated)
        after = derotate._getAngle(invertedDerotated)

        self.assertLessEqual(abs(after), abs(before))
        self.assertLessEqual(abs(after), 10.0)
Exemplo n.º 6
0
	def threshold(img, thresh):
		"""Threshold an image"""
		
		pilIMG1 = Image.fromarray(img);
		pilInverted1 = ImageOps.invert(pilIMG1);
		inverted = np.asarray(pilInverted1);
		r, t = cv2.threshold(inverted, thresh, 0, type=cv.CV_THRESH_TOZERO);
		pilIMG2 = Image.fromarray(t);
		pilInverted2 = ImageOps.invert(pilIMG2);
		thresholded = np.asarray(pilInverted2);
		return thresholded;
Exemplo n.º 7
0
    def _derotationTest(self, imageName):
        image = samples.getSample("algorithmTests", imageName)[0]
        inverted = ImageOps.invert(image.convert("L"))
        before = derotate._getAngle(inverted)

        derotated = derotate.derotate(image)
        invertedDerotated = ImageOps.invert(derotated)
        after = derotate._getAngle(invertedDerotated)

        self.assertLessEqual(abs(after), abs(before))
        self.assertLessEqual(abs(after), 10.0)
Exemplo n.º 8
0
    def threshold(img, thresh):
        """Threshold an image"""

        pilIMG1 = Image.fromarray(img)
        pilInverted1 = ImageOps.invert(pilIMG1)
        inverted = numpy.asarray(pilInverted1)
        r, t = cv2.threshold(inverted, thresh, 0, type=cv.CV_THRESH_TOZERO)
        pilIMG2 = Image.fromarray(t)
        pilInverted2 = ImageOps.invert(pilIMG2)
        thresholded = numpy.asarray(pilInverted2)
        return thresholded
Exemplo n.º 9
0
def WriteLayerIMG(ifn, z, allpoints, siz, scale, pan, colour, mode):
    scx, scy = scale
    panx, pany = pan
    sizex, sizey = siz
    img = Image.new(mode, (int(sizex), int(sizey)), colour[0])
    draw = ImageDraw.Draw(img)
    
    allpoints = ContourNesting(allpoints)
    

    # sort into core and cavity:
    cores = []
    cavities = []
    for cc, points in allpoints:
        iscavity = cc == "cavity" or cc == True
        if iscavity:
            cavities.append(points)
        else:
            cores.append(points)
            
    for cavity, points in allpoints:
        iscavity = cavity == "cavity" or cavity == True
        pts = [(x * scx + panx, y * scy + pany) for x, y in points]
        if len(pts) == 1 or pts[0] != pts[-1]:
            draw.line(pts, fill=colour[2])
            ms = 3 # 3 pixel marker
            for x, y in pts:
                draw.polygon([(x - ms, y - ms), (x + ms, y - ms), (x + ms, y + ms), (x - ms, y + ms)], fill=colour[2])
        else:
            draw.polygon(pts, fill=(iscavity and colour[1] or colour[2]))
    
    # -- Additions begin here --
    invertedImage = ImageOps.invert(img)
    
    if invertedImage.getbbox():
    	# Set image to 75% of its original size
		invertedImage = invertedImage.resize((365,411))
		invertedImage = ImageOps.invert(invertedImage)
		
		img_w,img_h=invertedImage.size
		background = Image.new('RGB', (608,684), (255, 255, 255))
		bg_w,bg_h=background.size
		offset=((bg_w-img_w)/2, (bg_h-img_h)/2)
		background.paste(invertedImage,offset)
		newBackground = ImageOps.invert(background)
		
		#invertedImage = invertedImage.resize((304,342))
  		newBackground.save(ifn)
    else:
	  	open(ifn[:-3]+"temp","w")
Exemplo n.º 10
0
	def mask_q0(self, pixbuf, selection):
		q0_cell_size = 8
		w = selection[2]
		h = selection[3]
		ow = pixbuf.get_width()
		oh = pixbuf.get_height()
		im = Image.new("RGB", (w, h))
		fullimage = Image.fromstring("RGB", (ow, oh), pixbuf.get_pixels())
		temp = fullimage.crop((selection[0], selection[1], selection[0] + w, selection[1] + h))

		cell_width = w / q0_cell_size
		cell_height = h / q0_cell_size

		for y in xrange(cell_height):
			for x in xrange(cell_width):
				px = q0_cell_size * x
				py = q0_cell_size * y
				for yy in xrange(q0_cell_size):
					for xx in xrange(q0_cell_size):
						im.putpixel(((px + q0_cell_size - xx - 1), (py + q0_cell_size - yy - 1)), temp.getpixel(((px + xx), (py + yy))))

		im = ImageOps.invert(im)

		fullimage.paste(im, (selection[0], selection[1]))

		return gtk.gdk.pixbuf_new_from_data(fullimage.tostring(), gtk.gdk.COLORSPACE_RGB, False, 8, ow, oh, 3 * ow)
Exemplo n.º 11
0
    def _measure_photo(self, i):
        '''Record and calculate various attributes of a photo'''
        # open file
        image = Image.open(self.photo_paths[i])

        # get x & y pixel counts
        width, height = image.size
        self.image_size_pixels[i] = [height, width]

        # find object in image: calc size in pixels
        image_inverted = ImageOps.invert(image)
        bbox = image_inverted.getbbox()
        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]
        self.object_size_pixels[i] = [h, w]

        # calc size of object in radians
        is_vertical = False
        if height > width:
            is_vertical = True
        width_frac = (w / float(width))
        height_frac = (h / float(height))
        if is_vertical:
            width_rads = width_frac * self.fov_smaller
            height_rads = height_frac * self.fov_larger
        else:
            width_rads = width_frac * self.fov_larger
            height_rads = height_frac * self.fov_smaller
        self.object_size_radians[i] = [height_rads, width_rads]
Exemplo n.º 12
0
def imagetogcode(image, f):
    
    img = ImageOps.invert(image)
    width, height = img.size

    f.write("; Image pixel size: "+str(width)+"x"+str(height)+"\n");

    pixels = list(img.getdata())
    pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
    forward = True

    def get_chunks(arr, chunk_size = 51):
        chunks  = [ arr[start:start+chunk_size] for start in range(0, len(arr), chunk_size)]
        return chunks
    
    for row in reversed(pixels):
        first = True        
        if not forward:
            result_row = row[::-1]
        else:
            result_row = row
        for chunk in get_chunks(result_row):
            if first:
                if forward:
                    f.write("G7 N1 ")
                else:
                    f.write("G7 N0 ")
                first = not first
            else:
                f.write ("G7")
            b64 = base64.b64encode("".join(chr(x) for x in chunk))
            f.write("L"+str(len(b64))+" ")
            f.write("D"+b64+ "\n")
        forward = not forward
Exemplo n.º 13
0
    def addUniqueData(self, filename, inputType, normalized=False):
        import os
        if not os.path.isfile(filename):
            raise Exception("addUniqueData : \"" + filename + "\" is not a file")
        if inputType >= DataCategory.TRAIN and inputType <= DataCategory.TEST:
            im = Normalize(self.Size(), filename, offset=self.__offset)
            array = []
            import ImageOps
            if self.__grayScale:
                im = ImageOps.grayscale(im)
                if self.__negate:
                    im = ImageOps.invert(im)
                if normalized:
                   array = [float(x) / 255. for x in list(im.getdata())]
                else:
                   array = [x for x in list(im.getdata())]
            else:
                for p in list(im.getdata()):
#                    array.append(zip([float(x)/255. for x in p]))
                    for i in xrange(len(p)):
                        if normalized:
                            array.append(float(p[i]) / 255.)
                        else:
                            array.append(p[i])
                    array = [x for x in array]
            self.Inputs()[inputType].append(array)
            import string
            groundTruth = string.split(os.path.splitext(os.path.split(filename)[1])[0], '-')[0]
            self.Targets()[inputType].append(int(groundTruth))
        else:
            raise Exception("Incorrect DataCategory")
Exemplo n.º 14
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
Exemplo n.º 15
0
    def execute(self):
        import Image
        import ImageOps
        i = Image.open(self.target)
        i = i.convert("RGB")
        if getattr(self, 'brightness', None):
            i = i.point(lambda p: p * self.brightness)
        r, g, b = i.split()
        a = {
            'r': r,
            'g': g,
            'b': b,
            'x': Image.new("L", r.size, color=0),
        }.get(self.level)
        if not a:
            a = Image.new("L", r.size, color=self.level)
        if self.level == 'x':
            pxi = i.load()
            pxa = a.load()
            for y in xrange(a.size[1]):
                for x in xrange(a.size[0]):
                    p = pxi[x, y]
                    pxa[x, y] = int((p[0] + p[1] + p[2]) / 3.0)
            
            
        if getattr(self, 'invert_alpha', None):
            a = ImageOps.invert(a)
        i2 = Image.merge("RGBA", (r, g, b, a))
        i2.save(self.target)

        """
Exemplo n.º 16
0
def preprocess_image(f):
    io = StringIO(f)
    im = Image.open(io)
    im = ImageOps.autocontrast(im)
    im = brighten(im, 2.1)
    im = ImageOps.grayscale(im)
    im = ImageOps.invert(im)
    im = im.point(lambda i: 250 if i > 1 else i)
    im = ImageOps.invert(im)
    im = clear_noise(im, 254, 1, 255)

    io = StringIO()
    im.save(io, "png")
    ret = io.getvalue()
    io.close()
    return ret
Exemplo n.º 17
0
    def on_send_button_clicked(self, event):
        if self.monitor is None:
            img_data = self.painter.get_image_data()
            #prepare an image
            w, h, d = img_data.shape
            img = Image.fromstring( "RGBA", ( w ,h ), img_data.tostring() )
            img_gs = img.convert('L')
            # thumbnail_size = (28, 28)
            # img_gs.thumbnail(thumbnail_size)
            img_gs_inv = ImageOps.invert(img_gs)
        else:
            img_data = self.monitor.get_image_data()
            # img_gs_inv = 255 - img_data
            img_gs_inv = img_data


        img_gs_inv_thumbnail, bound_rect = utils.get_char_img_thumbnail_helper(np.asarray(img_gs_inv))
        # img.show()
        self.img_data = np.asarray(img_gs_inv_thumbnail).flatten().astype(np.float32) * 1./255.
        if self.on_send_usr_callback is not None:
            self.on_send_usr_callback(self)
            #update the target canvas
            self.ax_target.imshow(self.img_data.reshape((28, 28)))
            self.target_canvas.draw()
        return
Exemplo n.º 18
0
    def on_send_incomplete_button_clicked(self, event):
        if self.monitor is None:
            img_data = self.painter.get_image_data()
        else:
            img_data = self.monitor.get_image_data()

        #prepare an image
        w, h, d = img_data.shape
        img = Image.fromstring( "RGBA", ( w ,h ), img_data.tostring() )
        img_gs = img.convert('L')
        # thumbnail_size = (28, 28)
        # img_gs.thumbnail(thumbnail_size)
        img_gs_inv = ImageOps.invert(img_gs)
        img_gs_inv_thumbnail, bound_rect = utils.get_char_img_thumbnail_helper(np.asarray(img_gs_inv))
        # img.show()
        self.img_data = np.asarray(img_gs_inv_thumbnail).flatten().astype(np.float32) * 1./255.

        #cover a fraction of the image to produce incomplete data
        self.fraction_idx = (np.random.rand(2) > 0.5).astype(int)
        self.img_incomplete_data = self.img_data.reshape((28, 28))
        self.img_incomplete_data[14*self.fraction_idx[0]:14*(self.fraction_idx[0]+1), 14*self.fraction_idx[1]:14*(self.fraction_idx[1]+1)] = 0
        self.img_incomplete_data = self.img_incomplete_data.flatten()

        if self.on_send_incomplete_usr_callback is not None:
            self.on_send_incomplete_usr_callback(self)
            #update the target canvas
            self.ax_target.imshow(self.img_data.reshape((28, 28)))
            self.target_canvas.draw()
        return
Exemplo n.º 19
0
def gen_captcha(text, fontname, fontsize, file_name):
    """Generate a captcha image"""
    # white text on a black background
    bgcolor = 0x0
    fgcolor = 0xffffff
    # create a font object
    font = ImageFont.truetype(fontname, fontsize)
    # determine dimensions of the text
    dim = font.getsize(text)
    # create a new image significantly larger that the text
    edge = max(dim[0], dim[1]) + 2 * min(dim[0], dim[1])
    im = Image.new('RGB', (edge, edge), bgcolor)
    d = ImageDraw.Draw(im)
    x, y = im.size
    # add the text to the image
    d.text((x / 2 - dim[0] / 2, y / 2 - dim[1] / 2),
           text,
           font=font,
           fill=fgcolor)
    k = 2
    wob = 0.09 * dim[1]
    rot = 45
    # Apply lots of small stirring operations, rather than a few large ones
    # in order to get some uniformity of treatment, whilst
    # maintaining randomness
    for i in range(k):
        im = wobbly_copy(im, wob, bgcolor, i * 2 + 3, rot + 0)
        im = wobbly_copy(im, wob, bgcolor, i * 2 + 1, rot + 45)
        im = wobbly_copy(im, wob, bgcolor, i * 2 + 2, rot + 90)
        rot += 30

    # now get the bounding box of the nonzero parts of the image
    bbox = im.getbbox()
    bord = min(dim[0], dim[1]) / 4  # a bit of a border
    im = im.crop(
        (bbox[0] - bord, bbox[1] - bord, bbox[2] + bord, bbox[3] + bord))

    # Create noise
    nblock = 4
    nsize = (im.size[0] / nblock, im.size[1] / nblock)
    noise = Image.new('L', nsize, bgcolor)
    data = noise.load()
    for x in range(nsize[0]):
        for y in range(nsize[1]):
            r = random.randint(0, 65)
            gradient = 70 * x / nsize[0]
            data[x, y] = r + gradient
    # Turn speckles into blobs
    noise = noise.resize(im.size, Image.BILINEAR)
    # Add to the image
    im = ImageMath.eval('convert(convert(a, "L") / 3 + b, "RGB")',
                        a=im,
                        b=noise)

    # and turn into black on white
    im = ImageOps.invert(im)

    # save the image, in format determined from filename
    im.save(file_name)
Exemplo n.º 20
0
def showResult(result, dims, k=2):
    i = Image.new("L", dims)
    i.putdata(result, (255 / (k - 1)))
    i = i.crop(i.getbbox())
    i = ImageOps.invert(i)
    i.load()
    #i.show()
    i.save("bs.png","PNG")
Exemplo n.º 21
0
def push_face(weather):
    image = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 1)
    draw = ImageDraw.Draw(image)
    tt_img = get_sessions()
    image.paste(tt_img, (0, EPD_HEIGHT - TT_HEIGHT))
    time_y = TOP_MARGIN
    time_x = LEFT_MARGIN
    #draw.rectangle(((LEFT_MARGIN, TOP_MARGIN), (640-256, 296)))
    #draw.rectangle(((640-256, TOP_MARGIN), (640, 256)))
    #draw.rectangle(((640-256, 256), (640, 296)))
    draw.rectangle(((1, 296), (639, 383)))

    time, day, date = get_clock_data()

    time_width = EPD_WIDTH - LEFT_MARGIN - IMAGE_SIZE
    time_sp_y = (EPD_HEIGHT - TT_HEIGHT) // 2
    day_sp_y = time_sp_y // 2
    date_sp_y = day_sp_y
    time_font_size = max_font_size(TIME_FONT, time, time_width, time_sp_y)
    day_font_size = max_font_size(TIME_FONT, day, time_width, day_sp_y)
    date_font_size = max_font_size(TIME_FONT, date, time_width, date_sp_y)

    time_tf = ImageFont.truetype(TIME_FONT, time_font_size)
    day_tf = ImageFont.truetype(TIME_FONT, day_font_size)
    date_tf = ImageFont.truetype(TIME_FONT, date_font_size)

    time_height, time_offset = get_line_height(time, time_tf)
    time_height = time_tf.getsize(time)[1]
    day_height, date_offset = get_line_height(day, day_tf)
    day_height = day_tf.getsize(day)[1]
    day_y = time_y + time_height
    date_y = day_y + day_height
    draw.text((time_x, time_y), time, font=time_tf, fill=0)
    draw.text((time_x, day_y), day, font=day_tf, fill=0)
    draw.text((time_x, date_y), date, font=date_tf, fill=0)

    weather_img = Image.open(LIB_DIR + weather.img, 'r')
    image.paste(weather_img, (EPD_WIDTH - IMAGE_SIZE, TOP_MARGIN),
                mask=weather_img)
    weather_text = weather.condition.text + ', ' + weather.condition.temp
    weather_font_size = max_font_size(WEATHER_FONT, weather_text + 'o',
                                      IMAGE_SIZE,
                                      EPD_HEIGHT - IMAGE_SIZE - TT_HEIGHT)
    weather_tf = ImageFont.truetype(WEATHER_FONT, weather_font_size)
    weather_text_width, weather_text_height = weather_tf.getsize(weather_text)
    weather_text_x = EPD_WIDTH - IMAGE_SIZE + (IMAGE_SIZE -
                                               weather_text_width) // 2
    weather_text_position = (weather_text_x, IMAGE_SIZE)
    draw.text(weather_text_position, weather_text, font=weather_tf, fill=0)
    degree_top = (weather_text_position[0] + weather_text_width,
                  weather_text_position[1])
    degree_bottom = (degree_top[0] + 7, degree_top[1] + 7)
    degree_box = (degree_top, degree_bottom)
    draw.ellipse(degree_box, fill=None, outline='black')
    if weather.night:
        image = image.convert('L')
        image = ImageOps.invert(image)
    epd.display_frame(epd.get_frame_buffer(image))
Exemplo n.º 22
0
 def add_image(self, image):
     """
     Adds the data of a PIL image as a frame to the current movie.
     """
     if self.inverted:
         import ImageOps
         image_inv = ImageOps.invert(image)
         self._add_file(image_inv.save)
     else:
         self._add_file(image.save)
Exemplo n.º 23
0
    def get_blinds(self):
        box = (39, 522, 288, 552)
        time.sleep(2)
        img = ImageGrab.grab(box)
        img = img.convert('L')
        enh = ImageEnhance.Contrast(img)
        img = enh.enhance(2)
        img = ImageOps.invert(img)
        img.show()

        print image_to_string(img)
Exemplo n.º 24
0
def sketch(image, details_degree=1):
    im1 = image.convert('L')
    im2 = im1.copy()

    im2 = ImageOps.invert(im2)
    for i in xrange(details_degree):
        im2 = im2.filter(ImageFilter.BLUR)
    im1 = ImageMath.eval('convert(min(a * 255/ (256 - b), 255), "L")',
            a=im1,
            b=im2)
    return im1
Exemplo n.º 25
0
def sketch(image, details_degree=1):
    im1 = image.convert('L')
    im2 = im1.copy()

    im2 = ImageOps.invert(im2)
    for i in xrange(details_degree):
        im2 = im2.filter(ImageFilter.BLUR)
    im1 = ImageMath.eval('convert(min(a * 255/ (256 - b), 255), "L")',
                         a=im1,
                         b=im2)
    return im1
Exemplo n.º 26
0
def ndarray2image(data, filename):
    """ 
    writes content of float ndarray as .png file.
    normalizes content and writes uint8 picture
    """
    #scale image to uint8
    data = (255.0 / data.max() * (data - data.min())).astype(np.uint8)
    im = Image.fromstring("L", (data.shape[1], data.shape[0]), raw.tostring())
    im = ImageOps.autocontrast(im)
    im = ImageOps.invert(im)
    im.save(filename)
Exemplo n.º 27
0
 def __call__(self, img_ref):
     img = img_ref.get_image()
     if img.mode == '1':
         img = ImageOps.grayscale(img)
     elif img.mode != 'L':
         return img_ref
     h = img.histogram()
     if sum(h[:64]) < img.size[0] * img.size[1] / 2:
         return img_ref
     img = ImageOps.invert(img)
     return ImageRef(img)
Exemplo n.º 28
0
def gen_captcha(text, fontname, fontsize, file_name):
	"""Generate a captcha image"""
	# white text on a black background
	bgcolor = 0x0
	fgcolor = 0xffffff
	# create a font object 
	font = ImageFont.truetype(fontname,fontsize)
	# determine dimensions of the text
	dim = font.getsize(text)
	# create a new image significantly larger that the text
	edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1])
	im = Image.new('RGB', (edge, edge), bgcolor)
	d = ImageDraw.Draw(im)
	x, y = im.size
	# add the text to the image
	d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor)
	k = 2
	wob = 0.09*dim[1]
	rot = 45
	# Apply lots of small stirring operations, rather than a few large ones
	# in order to get some uniformity of treatment, whilst
	# maintaining randomness
	for i in range(k):
		im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0)
		im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45)
		im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90)
		rot += 30
	
	# now get the bounding box of the nonzero parts of the image
	bbox = im.getbbox()
	bord = min(dim[0], dim[1])/4 # a bit of a border
	im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord))

	# Create noise
	nblock = 4
	nsize = (im.size[0] / nblock, im.size[1] / nblock)
	noise = Image.new('L', nsize, bgcolor)
	data = noise.load()
	for x in range(nsize[0]):
		for y in range(nsize[1]):
			r = random.randint(0, 65)
			gradient = 70 * x / nsize[0]
			data[x, y] = r + gradient
	# Turn speckles into blobs
	noise = noise.resize(im.size, Image.BILINEAR)
	# Add to the image
	im = ImageMath.eval('convert(convert(a, "L") / 3 + b, "RGB")', a=im, b=noise)

	# and turn into black on white
	im = ImageOps.invert(im)

	# save the image, in format determined from filename
	im.save(file_name)
Exemplo n.º 29
0
def get_sessions():
    tt_img = Image.new('1', (EPD_WIDTH, TT_HEIGHT), 1)
    tt_connection = sqlite3.connect(LIB_DIR + 'timetable.sqlite')
    tt_connection.row_factory = sqlite3.Row
    tt_cursor = tt_connection.cursor()
    current_time = datetime.datetime.now()
    hour = int(current_time.strftime('%H%M'))
    day = current_time.strftime('%A')
    session_sql = """SELECT s.session_number, s.title, s.start_time, s.end_time,
                          e.year_group, e.event_details, e.location
                   FROM sessions s, timetable_days d
                   LEFT JOIN events e on e.session_number = s.session_number 
                     AND e.day = ?
                   WHERE s.timetable_code = d.tt_code AND d.day = ?"""
    shrt = 50
    lng = 78
    next_session_x = 0
    for row in tt_cursor.execute(session_sql, (day, day)):
        start_time = datetime.datetime.strptime(row['start_time'], '%H%M')
        end_time = datetime.datetime.strptime(row['end_time'], '%H%M')
        title = row['title']
        session_number = row['session_number']
        year = row['year_group']
        event = row['event_details']
        location = row['location']
        duration = end_time - start_time
        long_session = duration.total_seconds() > 50 * 60
        if long_session:
            cell_width = lng
        else:
            cell_width = shrt
        session_img = Image.new('1', (cell_width, TT_HEIGHT), 1)
        session_canvas = ImageDraw.Draw(session_img)
        text_y = 0
        session_canvas.line((0, 0, 0, TT_HEIGHT))
        text_y = write_session_text(text_y, title, cell_width - 2,
                                    session_canvas)
        if year:
            text_y = write_session_text(text_y, year, cell_width,
                                        session_canvas)
        if event:
            text_y = write_session_text(text_y, event, cell_width,
                                        session_canvas)
        if location:
            text_y = write_session_text(text_y, location, cell_width,
                                        session_canvas)
        if int(row['start_time']) <= hour and hour <= int(row['end_time']):
            session_img = session_img.convert('L')
            session_img = ImageOps.invert(session_img)
        tt_img.paste(session_img, (next_session_x, 0))
        next_session_x = next_session_x + cell_width
    return tt_img
Exemplo n.º 30
0
def convert( srcimg, manul, w, h, optionString, dstname ):
    name = manul.filename
    srcw, srch = srcimg.size
    ratiow, ratioh = w/float(srcw), h/float(srch)
    roi = manul.region
    if ratiow != 1 and ratioh != 1:
        if ratioh > ratiow:
            desth = h
            destw = int( math.ceil( srcw * desth / float(srch)) )
        else:
            destw = w
            desth = int( math.ceil( srch * destw / float(srcw)) )
        srcimg = srcimg.resize( (destw,desth), Image.ANTIALIAS )
        if roi:
            (x0,y0), (x1,y1) = roi
            x0 *= destw / float(srcw )
            x1 *= destw / float(srcw )
            y0 *= desth / float(srch )
            y1 *= desth / float(srch )
            roi = (x0,y0), (x1,y1)
        srcw, srch = destw, desth
    assert (srcw == w) or (srch == h)
    assert (srcw >=  w) and (srch >= h)
    if srcw > w:
        if not roi:
            pad = int( (srcw - w) / 2 )
        else:
            (x0,y0), (x1,y1) = roi
            poix = (x0+x1)/2.0
            pad = min( srcw - w, max(0, int(poix - w/2)) )
        srcimg = srcimg.crop( (pad,0,pad+w-1,h-1) )
    elif srch > h:
        if not roi:
            pad = int( (srch - h) / 2 )
        else:
            (x0,y0), (x1,y1) = roi
            poiy = (y0+y1)/2.0
            pad = min( srch - h, max(0,int(poiy - h/2)) )
        srcimg = srcimg.crop( (0,pad,w-1,pad+h-1) )
    for option in optionString:
        if option == "g":
            srcimg = ImageOps.grayscale( srcimg )
        elif option == "n":
            srcimg = ImageOps.invert( srcimg )
        elif option == "s":
            sepia = 0xff, 0xf0, 0xc0
            srcimg = srcimg.convert( "L" )
            srcimg.putpalette( [ int( (i/3/255.0) * sepia[i%3] ) for i in range(256*3) ] )
            srcimg = srcimg.convert( "RGB" )
    # todo locking, write to temp and then copy
    srcimg.save( dstname )
    return True
Exemplo n.º 31
0
def drawing(infile, outfile, blur=25, alpha=1.0):
    im1 = Image.open(infile).convert("L")
    im2 = im1.copy()
    im2 = ImageOps.invert(im2)
    for i in range(blur):
        im2 = im2.filter(ImageFilter.BLUR)
    width, height = im1.size
    for x in range(width):
        for y in range(height):
            a = im1.getpixel((x, y))
            b = im2.getpixel((x, y))
            im1.putpixel((x, y), dodge(a, b, alpha))
    im1.save(outfile)
Exemplo n.º 32
0
 def add_image(self, image):
     """
     Adds the data of a PIL image as a frame to the current movie.
     """
     if self.inverted:
         try:
             import ImageOps
         except ImportError:
             from PIL import ImageOps
         image_inv = ImageOps.invert(image)
         self._add_file(image_inv.save)
     else:
         self._add_file(image.save)
Exemplo n.º 33
0
def trim(im):
	bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
	diff = ImageChops.difference(im, bg)
	diff = ImageChops.add(diff, diff, 2.0, -100)
	bbox = diff.getbbox();
	
	s = max([bbox[2]-bbox[0], bbox[3]-bbox[1]])
	center = [(bbox[2]+bbox[0])/2, (bbox[3]+bbox[1])/2]
	
	bbox = [center[0]-s/2, center[1]-s/2, center[0]+s/2, center[1]+s/2]
	
	if bbox:
		
		if im.mode == 'RGBA':
			r,g,b,a = im.split()
			im = Image.merge('RGB', (r,g,b))
			
		im = ImageOps.invert(im)
		crop = im.crop(bbox)
		
		return ImageOps.invert(crop)
	else: return im
Exemplo n.º 34
0
def _transform_img(img_base64):
    img = img_base64.decode("base64")

    img = Image.open(StringIO.StringIO(img)).convert('L')
    img = ImageOps.invert(img)
    img_data = img_to_img_data(img)
    img = img.crop(_find_bounds(img_data))
    # img.thumbnail((IMG_SIZE-2, IMG_SIZE-2), PIL.Image.NEAREST)
    # img_data = img_to_img_data(img)
    # img_data = resize(img_data, IMG_SIZE)
    img = img.resize((IMG_SIZE, IMG_SIZE))
    img_data = img_to_img_data(img)
    # return Image.fromarray(img_data), img_data
    return img, img_data
Exemplo n.º 35
0
def get_line_ccs(im):
	high_im = imageutils.binary(im, HIGH_THRESH)
	high_im = ImageOps.invert(high_im)
	#high_im.save("high_im.pgm")
	high_cc_im, high_ccs = ld.find_ccs(high_im)
	#print "Num ccs in high: ", len(high_ccs)
	#map(lambda cc: cc.display(), high_ccs)
	high_ccs = filter(lambda cc: cc_size(cc, high_cc_im.size), high_ccs)
	#print "Num ccs in high after filtering: ", len(high_ccs)
	#map(lambda cc: cc.display(), high_ccs)
	cc_points = map(lambda cc: cc.coords[0], high_ccs)

	low_im = imageutils.binary(im, LOW_THRESH)
	low_im = ImageOps.invert(low_im)
	#low_im.save("low_im.pgm")
	low_cc_im, low_ccs = ld.find_ccs(low_im)
	#print "Num ccs in low: ", len(low_ccs)
	#map(lambda cc: cc.display(), low_ccs)
	low_ccs = filter(lambda cc: cc_contains_any(cc, cc_points), low_ccs)
	#print "Num ccs in low after filtering: ", len(low_ccs)
	#map(lambda cc: cc.display(), low_ccs)

	return low_ccs
Exemplo n.º 36
0
def conn_comp(outname):
    '''
    Returns the number of connected components. Has to invert the file first since
    we want the number of black components (assumes white components is always 1)
    then uses scipy library to get number of disconnected components.
    '''
    #first invert the image
    im = Image.open(outname)
    inverted = io.invert(im)
    inverted.save('inverted.ppm')

    image = ndimage.imread('inverted.ppm')
    a, num_comp = ndimage.measurements.label(image)
    return num_comp
Exemplo n.º 37
0
 def process(self, _edObject=None):
     EDPluginExec.process(self)
     imageFileName = os.path.basename(self.dataInput.image.path.value)
     # Default format
     strSuffix = "jpg"
     strPILFormat = "JPEG"
     # Check if format is provided
     if self.dataInput.format is not None:
         strFormat = self.dataInput.format.value
         if strFormat.lower() == "png":
             strSuffix = "png"
             strPILFormat = "PNG"
     # The following code has been adapted from EDPluginExecThumbnail written by J.Kieffer
     fabioImage = fabio.openimage.openimage(self.dataInput.image.path.value)
     numpyImage = fabioImage.data
     dtype = numpyImage.dtype
     sortedArray = numpyImage.flatten()
     sortedArray.sort()
     numpyImage = numpy.maximum(
         numpyImage,
         int(self.minLevel) * numpy.ones_like(numpyImage))
     maxLevel = sortedArray[int(
         round(float(self.maxLevel) * sortedArray.size / 100.0))]
     numpyImage = numpy.minimum(numpyImage,
                                maxLevel * numpy.ones_like(numpyImage))
     numpyImage = scipy.ndimage.morphology.grey_dilation(
         numpyImage, (self.dilatation, self.dilatation))
     mumpyImageFloat = (numpyImage.astype(numpy.float32)) / float(maxLevel)
     numpyImageInt = (mumpyImageFloat * 255.0).astype(numpy.uint8)
     pilOutputImage = ImageOps.invert(Image.fromarray(numpyImageInt, 'L'))
     if self.dataInput.height is not None and self.dataInput.width is not None:
         pilOutputImage = pilOutputImage.resize(
             (self.dataInput.width.value, self.dataInput.height.value),
             Image.ANTIALIAS)
     if self.dataInput.outputPath is None:
         outputPath = os.path.join(
             self.getWorkingDirectory(),
             os.path.splitext(imageFileName)[0] + "." + strSuffix)
     else:
         outputPath = self.dataInput.outputPath.path.value
     self.DEBUG("Output thumbnail path: %s" % outputPath)
     self.width, self.height = pilOutputImage.size
     if self.width * self.height > ImageFile.MAXBLOCK:
         ImageFile.MAXBLOCK = self.width * self.height
     pilOutputImage.save(outputPath,
                         strPILFormat,
                         quality=85,
                         optimize=True)
     self.dataOutput.thumbnail = XSDataFile(XSDataString(outputPath))
Exemplo n.º 38
0
def gen_captcha(text, fontname, fontsize, file_name):
    """Generate a captcha image"""
    # white text on a black background
    bgcolor = 0x0
    fgcolor = 0xffffff
    # create a font object
    font = ImageFont.truetype(fontname, fontsize)
    # determine dimensions of the text
    dim = font.getsize(text)
    # create a new image significantly larger that the text
    edge = max(dim[0], dim[1]) + 2 * min(dim[0], dim[1])
    im = Image.new('RGB', (edge, edge), bgcolor)
    d = ImageDraw.Draw(im)
    x, y = im.size
    # add the text to the image
    d.text((x / 2 - dim[0] / 2, y / 2 - dim[1] / 2),
           text,
           font=font,
           fill=fgcolor)
    k = 3
    wob = 0.20 * dim[1] / k
    rot = 45
    # Apply lots of small stirring operations, rather than a few large ones
    # in order to get some uniformity of treatment, whilst
    # maintaining randomness
    for i in range(k):
        #		im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0)
        #		im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45)
        #		im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90)
        im = wobbly_copy(im, wob, bgcolor, i, rot + 0)
        im = wobbly_copy(im, wob, bgcolor, i, rot + 45)
        im = wobbly_copy(im, wob, bgcolor, i, rot + 90)
        rot += 30

    # now get the bounding box of the nonzero parts of the image
    bbox = im.getbbox()
    bord = min(dim[0], dim[1]) / 4  # a bit of a border
    im = im.crop(
        (bbox[0] - bord, bbox[1] - bord, bbox[2] + bord, bbox[3] + bord))
    # and turn into black on white
    im = ImageOps.invert(im)

    # save the image, in format determined from filename
    im.save(file_name)
def paint_lines(picture, coords, direction):
    width, height = picture.size
    outimg = Image.new('L', (width, height))
    outpixels = outimg.load()
    v="vertical"
    h="horizontal"
    print "current coords: ", coords
    for coord in coords:
        if direction==v:
            max_line = height
        elif direction==h:
            max_line = width
        for i in xrange(max_line):
            if direction==v:
                outpixels[coord,i] = 255
            elif direction==h:
                #print "fail i: {0}\tfail coord: {1}".format(i, coord)
                outpixels[i,coord] = 255
    print "coords: ", coords
    return Image.blend(ImageOps.invert(outimg).convert("RGB"),picture.convert("RGB"),0.2)
Exemplo n.º 40
0
    def neg_cb(self, action):
        if self.selection is not None and self.selection[4] is False:
            w = self.selection[2]
            h = self.selection[3]
            ow = self.image.get_width()
            oh = self.image.get_height()
            im = Image.new("RGB", (w, h))
            fullimage = Image.fromstring("RGB", (ow, oh),
                                         self.image.get_pixels())
            temp = fullimage.crop(
                (self.selection[0], self.selection[1], self.selection[0] + w,
                 self.selection[1] + h))

            im = ImageOps.invert(temp)
            fullimage.paste(im, (self.selection[0], self.selection[1]))

            self.image = gtk.gdk.pixbuf_new_from_data(fullimage.tostring(),
                                                      gtk.gdk.COLORSPACE_RGB,
                                                      False, 8, ow, oh, ow * 3)
            self.invalidate()
Exemplo n.º 41
0
    def readNumber( cls, frame, cord, invert=False, minval=200, save=False, zoom=2, zmethod=Image.BICUBIC ):
        image = ImageOps.grayscale( frame.crop( cord ) )
        image = image.convert( 'RGB' )
        if invert:
            image = ImageOps.invert( image )
        image = ImageOps.autocontrast( image )

        pixdata = image.load()

        for y in xrange( image.size[1] ):
            for x in xrange( image.size[0] ):
                pix = pixdata[x, y]
                if pix[0] > minval and pix[1] > minval and pix[2] > minval:
                    pixdata[x, y] = ( 255, 255, 255 )

        image = image.resize( ( ( cord[2] - cord[0] ) * zoom, ( cord[3] - cord[1] ) * zoom ), zmethod )
        image = image.convert( 'RGB' )
        if save:
            image.save( '%s\\tmp\snapshot__%d.png' % ( os.getcwd(), int( time.time() ) ), 'PNG' )

        return image_to_string( image ).strip()
Exemplo n.º 42
0
def add_reflection(im, opacity=0.8):
    """ Returns the supplied PIL Image (im) with a reflection effect
    bgcolor  The background color of the reflection gradient
    amount   The height of the reflection as a percentage of the orignal image
    opacity  The initial opacity of the reflection gradient
    Originally written for the Photologue image management system for Django
    and Based on the original concept by Bernd Schlapsi
    """
    reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM)
    background = Image.new('RGBA', im.size)
    start = int(255 - 255 * opacity)
    steps = int(255)
    increment = (255 - start) / float(steps)
    mask = Image.new('L', (1, 255))
    for y in range(255):
        if y < steps:
            val = int(y * increment + start)
        else:
            val = 255
        mask.putpixel((0, y), val)

    alpha_mask = mask.resize(im.size)
    reflection = Image.composite(background, reflection, alpha_mask)
    invert_im = im.convert('RGB')
    real_pos = invert_im.getbbox()
    if real_pos[1] == 0:
        invert_im = ImageOps.invert(invert_im)
        real_pos = invert_im.getbbox()
    if real_pos is None:
        return im
    reflection_height = im.size[1]
    reflection = reflection.crop((0, 0, im.size[0], reflection_height))
    composite = Image.new('RGBA', (im.size[0], im.size[1] + reflection_height))
    reflection_y = real_pos[3] - real_pos[1]
    composite.paste(im, (0, 0), im)
    composite.paste(reflection, (0, reflection_y), reflection)
    return composite
Exemplo n.º 43
0
def imagetogcode(image, f):

    img = ImageOps.invert(image)
    width, height = img.size

    f.write("; Image pixel size: " + str(width) + "x" + str(height) + "\n")

    pixels = list(img.getdata())
    pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
    forward = True

    def get_chunks(arr, chunk_size=51):
        chunks = [
            arr[start:start + chunk_size]
            for start in range(0, len(arr), chunk_size)
        ]
        return chunks

    for row in reversed(pixels):
        first = True
        if not forward:
            result_row = row[::-1]
        else:
            result_row = row
        for chunk in get_chunks(result_row):
            if first:
                if forward:
                    f.write("G7 N1 ")
                else:
                    f.write("G7 N0 ")
                first = not first
            else:
                f.write("G7")
            b64 = base64.b64encode("".join(chr(x) for x in chunk))
            f.write("L" + str(len(b64)) + " ")
            f.write("D" + b64 + "\n")
        forward = not forward
def convert_image_to_sketch(image):
    im1 = image.convert("L")

    im2 = im1.copy()

    im2 = ImageOps.invert(im2)

    blur = 3

    for i in range(blur):
        im2 = im2.filter(ImageFilter.BLUR)

    alpha = 1

    width, height = im1.size
    for x in range(width):
        for y in range(height):
            a = im1.getpixel((x, y))
            b = im2.getpixel((x, y))
            im1.putpixel((x, y), dodge(a, b, alpha))

    im1 = im1.convert("RGB")

    return im1
Exemplo n.º 45
0
def paste(destination, source, box=(0, 0), mask=None, force=False):
    """"Pastes the source image into the destination image while using an
    alpha channel if available.

    :param destination: destination image
    :type destination:  PIL image object
    :param source: source image
    :type source: PIL image object
    :param box:

        The box argument is either a 2-tuple giving the upper left corner,
        a 4-tuple defining the left, upper, right, and lower pixel coordinate,
        or None (same as (0, 0)). If a 4-tuple is given, the size of the
        pasted image must match the size of the region.

    :type box: tuple
    :param mask: mask or None

    :type mask: bool or PIL image object
    :param force:

        With mask: Force the invert alpha paste or not.

        Without mask:

        - If ``True`` it will overwrite the alpha channel of the destination
          with the alpha channel of the source image. So in that case the
          pixels of the destination layer will be abandonned and replaced
          by exactly the same pictures of the destination image. This is mostly
          what you need if you paste on a transparant canvas.
        - If ``False`` this will use a mask when the image has an alpha
          channel. In this case pixels of the destination image will appear
          through where the source image is transparent.

    :type force: bool
    """
    # Paste on top
    if source == mask:
        if has_alpha(source):
            # invert_alpha = the transparant pixels of the destination
            if has_alpha(destination) and (destination.size == source.size
                                           or force):
                invert_alpha = ImageOps.invert(get_alpha(destination))
                if invert_alpha.size != source.size:
                    # if sizes are not the same be careful!
                    # check the results visually
                    if len(box) == 2:
                        w, h = source.size
                        box = (box[0], box[1], box[0] + w, box[1] + h)
                    invert_alpha = invert_alpha.crop(box)
            else:
                invert_alpha = None
            # we don't want composite of the two alpha channels
            source_without_alpha = remove_alpha(source)
            # paste on top of the opaque destination pixels
            destination.paste(source_without_alpha, box, source)
            if invert_alpha != None:
                # the alpha channel is ok now, so save it
                destination_alpha = get_alpha(destination)
                # paste on top of the transparant destination pixels
                # the transparant pixels of the destination should
                # be filled with the color information from the source
                destination.paste(source_without_alpha, box, invert_alpha)
                # restore the correct alpha channel
                destination.putalpha(destination_alpha)
        else:
            destination.paste(source, box)
    elif mask:
        destination.paste(source, box, mask)
    else:
        destination.paste(source, box)
        if force and has_alpha(source):
            destination_alpha = get_alpha(destination)
            source_alpha = get_alpha(source)
            destination_alpha.paste(source_alpha, box)
            destination.putalpha(destination_alpha)
Exemplo n.º 46
0
    def process(self, _edObject=None):
        """
        This is the main method of the plugin, it does the job, not the EDNA name conversions which were done in the preprocess. 
        """

        EDPluginExec.process(self)
        EDVerbose.DEBUG("EDPluginExecThumbnailv10.process")

        #        try:
        #        except Exception:
        #        edfImage = EDF(self.inputFilename)
        #        self.npaImage = edfImage.GetData(0)

        #        Read the image using FABIO
        isRGB = False
        pilOutputImage = None
        if self.inputFilename is not None:
            try:
                fabioImage = openimage(self.inputFilename)
                self.npaImage = fabioImage.data
            except Exception:
                pilInputImage = Image.open(self.inputFilename)
                x, y = pilInputImage.size
                ImageFile.MAXBLOCK = x * y
                if pilInputImage.mode == "1":
                    self.npaImage = numpy.asarray(pilInputImage).astype(
                        "uint8")
                    isRGB = False
                elif pilInputImage.mode == "F":
                    self.npaImage = numpy.asarray(pilInputImage)
                    isRGB = False
                elif pilInputImage.mode == "L":
                    self.npaImage = numpy.asarray(pilInputImage)
                    isRGB = False
                elif pilInputImage.mode == "P":
                    self.npaImage = numpy.asarray(pilInputImage.convert("RGB"))
                    isRGB = True
                elif pilInputImage.mode == "RGB":
                    self.npaImage = numpy.asarray(pilInputImage)
                    isRGB = True
                elif pilInputImage.mode == "CMJK":
                    self.npaImage = numpy.asarray(pilInputImage.convert("RGB"))
                    isRGB = True

        dtype = self.npaImage.dtype
        NPAImageFloat = None

        # crop border
        if len(self.cropBorders) > 0:

            if len(self.cropBorders) == 1:
                crop0 = self.cropBorders[0]
                crop1 = self.cropBorders[0]
            else:
                crop0 = self.cropBorders[0]
                crop1 = self.cropBorders[1]
            if isRGB:
                self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1, :]
            else:
                self.npaImage = self.npaImage[crop0:-crop0, crop1:crop1]

# Set maxima and minima
        if (self.minLevelUnit is not None) or (self.maxLevelUnit is not None):
            sortedArray = self.npaImage.flatten()
            sortedArray.sort()

        if self.minLevel is not None:
            self.normalize = True
            if isRGB:
                EDVerbose.warning(
                    "It is not allowed  to set Min with RGB data")
            else:
                if self.minLevelUnit in ["%", "percent"]:
                    self.minLevel = sortedArray[int(
                        round(float(self.minLevel) * sortedArray.size /
                              100.0))]
                if isinstance(self.npaImage[0, 0], int):
                    self.npaImage = numpy.maximum(
                        self.npaImage,
                        int(self.minLevel) * numpy.ones_like(self.npaImage))
                else:
                    self.npaImage = numpy.maximum(
                        self.npaImage,
                        self.minLevel * numpy.ones_like(self.npaImage))

        if self.maxLevel is not None:
            self.normalize = True
            if isRGB:
                EDVerbose.warning(
                    "It is not allowed  to set Max with RGB data")
            else:
                if self.maxLevelUnit in ["%", "percent"]:
                    self.maxLevel = sortedArray[int(
                        round(float(self.maxLevel) * sortedArray.size /
                              100.0))]
                if isinstance(self.npaImage[0, 0], int):
                    self.npaImage = numpy.minimum(
                        self.npaImage,
                        int(self.maxLevel) * numpy.ones_like(self.npaImage))
                else:
                    self.npaImage = numpy.minimum(
                        self.npaImage,
                        self.maxLevel * numpy.ones_like(self.npaImage))

# Scipy filters come here:
        if len(self.gaussianBlur) > 0:
            if len(self.gaussianBlur) == 1:
                kernel = (self.gaussianBlur[0], self.gaussianBlur[0])
            else:
                kernel = (self.gaussianBlur[0], self.gaussianBlur[1])
            if isRGB:
                kernel = (kernel[0], kernel[1], 0)
            self.npaImage = scipy.ndimage.gaussian_filter(
                self.npaImage, kernel)

        if len(self.dilatation) > 0:
            if len(self.dilatation) == 1:
                kernel = (self.dilatation[0], self.dilatation[0])
            else:
                kernel = (self.dilatation[0], self.dilatation[1])
            if isRGB:
                kernel = (kernel[0], kernel[1], 0)
            self.npaImage = scipy.ndimage.morphology.grey_dilation(
                self.npaImage, kernel)

#Normalization ; equalization
        if (self.normalize is True) or (self.equalize is True):
            if isRGB is True:
                self.npaImage = numpy.asarray(
                    ImageOps.equalize(Image.fromarray(self.npaImage)))
            else:
                EDVerbose.DEBUG("EDPluginExecThumbnailv10: Normalization")
                vmin = self.npaImage.min()
                vmax = self.npaImage.max()
                NPAImageFloat = (self.npaImage.astype(numpy.float32) -
                                 float(vmin)) / (float(vmax) - float(vmin))
                if (self.equalize == True):
                    nbr_bins = 64
                    NPAImageFloatFlat = NPAImageFloat.flatten()
                    imhist, bins = numpy.histogram(
                        NPAImageFloatFlat, nbr_bins,
                        normed=True)  #get image histogram
                    cdf = imhist.cumsum()  #cumulative distribution function
                    ncdf = cdf / cdf[
                        -1]  #normalized cumulative distribution function
                    #                    print ncdf
                    NPAImageFloat2Flat = numpy.interp(NPAImageFloatFlat, bins,
                                                      [0] + ncdf.tolist())
                    NPAImageFloat = NPAImageFloat2Flat.reshape(
                        NPAImageFloat.shape)
                    EDVerbose.DEBUG("Equalize: min= %f, max= %f" %
                                    (NPAImageFloat.min(), NPAImageFloat.max()))

#Gamma and logarithm scale
        if ((self.log is True) or (self.gamma != 1)) and (
                NPAImageFloat is None):  # then we need the array in float
            if dtype == numpy.uint8:
                NPAImageFloat = self.npaImage.astype(numpy.float32) / 255.0
            elif dtype == numpy.uint16:
                NPAImageFloat = self.npaImage.astype(numpy.float32) / 65535.0
            else:
                NPAImageFloat = self.npaImage.astype(numpy.float32)

        if self.log is True:
            NPAImageFloat = numpy.log(1 - NPAImageFloat.min() + NPAImageFloat)
            vmin = NPAImageFloat.min()
            vmax = NPAImageFloat.max()
            NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin)

        if self.gamma != 1:
            if dtype not in [numpy.uint8, numpy.uint16]:
                vmin = NPAImageFloat.min()
                vmax = NPAImageFloat.max()
                NPAImageFloat = (NPAImageFloat - vmin) / (vmax - vmin)
            NPAImageInt = (255.0 * (NPAImageFloat**self.gamma)).astype("uint8")

        else:  #if (self.gamma == 1):
            if NPAImageFloat is None:
                if dtype == numpy.uint8:
                    NPAImageInt = self.npaImage
                elif dtype == numpy.uint16:
                    NPAImageInt = (self.npaImage / 256).astype(numpy.uint8)
                else:  #for float or a signed integer
                    vmin = self.npaImage.min()
                    vmax = self.npaImage.max()
                    NPAImageInt = (
                        (self.npaImage.astype(numpy.float32) - vmin) /
                        (vmax - vmin) * 255.0).astype(numpy.uint8)
            else:
                vmin = NPAImageFloat.min()
                vmax = NPAImageFloat.max()
                EDVerbose.DEBUG(
                    "EDPluginExecThumbnailv10:   NPAImageFloat => NPAImageInt min=%s max =%s"
                    % (vmin, vmax))
                NPAImageInt = ((NPAImageFloat - vmin) * 255.0 /
                               (vmax - vmin)).astype(numpy.uint8)
#COnversion back to PIL mode
        if isRGB is True:
            pilOutputImage = Image.fromarray(NPAImageInt, 'RGB')
        else:
            pilOutputImage = Image.fromarray(NPAImageInt, 'L')

        if (self.autocontrast is not None):
            pilOutputImage = ImageOps.autocontrast(pilOutputImage,
                                                   self.autocontrast)

        if (self.width is not None) or (self.height is not None):
            if (self.width > 0) and (self.height > 0):
                if self.keepRatio is True:
                    #                    PIL takes care of the ratio
                    pilOutputImage.thumbnail((self.width, self.height),
                                             Image.ANTIALIAS)
                else:
                    pilOutputImage = pilOutputImage.resize(
                        (self.width, self.height), Image.ANTIALIAS)
            else:
                if self.width is None:
                    pilOutputImage.thumbnail((self.height, self.height),
                                             Image.ANTIALIAS)
                elif self.height is None:
                    pilOutputImage.thumbnail((self.width, self.width),
                                             Image.ANTIALIAS)

        if self.invert == True:
            pilOutputImage = ImageOps.invert(pilOutputImage)
        if self.colorize == True:
            pilOutputImage.putpalette(EDPluginExecThumbnailv10.getPalette())
            pilOutputImage = pilOutputImage.convert("RGB")

        self.synchronizeOn()
        if self.format == "jpg":
            self.width, self.height = pilOutputImage.size
            if self.width * self.height > ImageFile.MAXBLOCK:
                ImageFile.MAXBLOCK = self.width * self.height
            try:
                pilOutputImage.save(self.output,
                                    "JPEG",
                                    quality=85,
                                    optimize=True)
            except TypeError:
                pilOutputImage.save(self.output)
        else:
            pilOutputImage.save(self.output)
        self.synchronizeOff()
Exemplo n.º 47
0
		if allow_ML:
			raise('The selected portrait photo does not contain a depth map.')
		else:
			print('The selected portrait photo does not contain a depth map.')
			quit()
# If the selected photo does not contain a depth map, let's infer it using coreML
except Exception as e:
	# Hardcoded resolution for the Pydnet model
	chosen_pic_resized = chosen_pic.get_image(original = False).resize((640, 384))
	with io.BytesIO() as bts:
		chosen_pic_resized.save(bts, format = 'PNG')
		chosen_pic_depth = CoreML(bts).to_png()
	chosen_pic_depth_stream = io.BytesIO(chosen_pic_depth)
	chosen_pic_depth_image = Image.open(chosen_pic_depth_stream)
	chosen_pic_depth_image = chosen_pic_depth_image.resize((int(chosen_pic.get_ui_image().size[0]), int(chosen_pic.get_ui_image().size[1])), Image.BICUBIC)
	chosen_pic_depth_image = ImageOps.invert(chosen_pic_depth_image)
	# chosen_pic_depth_image.show()
	arr = numpy.array(chosen_pic_depth_image).astype(int)

# This part takes the depth map and normalizes its values to the range of (0, 180). You can experiment with the value, 255 is the ceiling.
chosen_pic_depth_image_array = (120*(arr - numpy.min(arr))/numpy.ptp(arr)).astype(int)
chosen_pic_depth_image = Image.fromarray(numpy.uint8(chosen_pic_depth_image_array))
# chosen_pic_depth_image = chosen_pic_depth_image.convert('P', palette = Image.ADAPTIVE, colors = 2)
# chosen_pic_depth_image.show()

# Making the images smaller for faster processing.
chosen_pic_image.thumbnail((350, 350), Image.ANTIALIAS)
chosen_pic_depth_image.thumbnail((350, 350), Image.ANTIALIAS)

# When the colormap mode is enabled, we use the colormapped depth data as a texture.
chosen_pic_photo_image_buffer = io.BytesIO()
Exemplo n.º 48
0
    def process(self, _edObject=None):
        """
        This is the main method of the plugin, it does the job, not the EDNA name conversions which were done in the preprocess. 
        """

        EDPluginExec.process(self)
        EDVerbose.DEBUG("EDPluginPyarchThumbnailv10.process")
        if self.inputFilename:
            #        Read the image using FABIO
            fabioImage = openimage(self.inputFilename)
            # Convert an FabioImage to a PIL image
            npaImageRaw = fabioImage.data

            iMinLevel = 2
            iMaxLevel = 1000
            npaImageRaw = numpy.minimum(
                npaImageRaw, iMaxLevel * numpy.ones_like(npaImageRaw))
            npaImageRaw = numpy.maximum(
                npaImageRaw, iMinLevel * numpy.ones_like(npaImageRaw))

            npaImage = scipy.ndimage.morphology.grey_dilation(npaImageRaw,
                                                              size=(5, 5))
            npaImageThumb = scipy.ndimage.morphology.grey_dilation(npaImageRaw,
                                                                   size=(10,
                                                                         10))

            dtype = str(npaImage.dtype)
            if dtype == "uint8":
                NPAImageFloat = npaImage.astype("float") / 255.0
                NPAImageFloatThumb = npaImageThumb.astype("float") / 255.0
            elif dtype == "uint16":
                NPAImageFloat = npaImage.astype("float") / 65535.0
                NPAImageFloatThumb = npaImageThumb.astype("float") / 65535.0
            else:  #for float or whatever
                vmin = npaImage.min()
                vmax = npaImage.max()
                NPAImageFloat = (npaImage.astype(float) - vmin) / (vmax - vmin)
                vminThumb = npaImageThumb.min()
                vmaxThumb = npaImageThumb.max()
                NPAImageFloatThumb = (npaImageThumb.astype(float) -
                                      vminThumb) / (vmax - vminThumb)

            NPAImageInt = (255.0 * (NPAImageFloat**0.3)).astype("uint8")
            NPAImageIntThumb = (255.0 *
                                (NPAImageFloatThumb**0.3)).astype("uint8")

            pilImage = Image.fromarray(NPAImageInt, 'L')
            pilImageThumb = Image.fromarray(NPAImageIntThumb, 'L')
            # For ISPyB we use for the moment only 1024x1024 and 256x256
            pilImage.thumbnail((1024, 1024), Image.ANTIALIAS)
            pilImageThumb.thumbnail((256, 256), Image.ANTIALIAS)

            pilImage = ImageOps.invert(pilImage)
            pilImageThumb = ImageOps.invert(pilImageThumb)

            self.synchronizeOn()
            if 1024 * 1024 > ImageFile.MAXBLOCK:
                ImageFile.MAXBLOCK = 1024 * 1024

            pilImage.save(self.strOutputPath,
                          "JPEG",
                          quality=50,
                          optimize=True)
            pilImageThumb.save(self.strOutputPathThumb,
                               "JPEG",
                               quality=85,
                               optimize=True)

            self.synchronizeOff()
Exemplo n.º 49
0
def imagetogcode(image, f):

    img = ImageOps.invert(image)
    width, height = img.size

    f.write("; Image pixel size: " + str(width) + "x" + str(height) + "\n")
    f.write("M649 S11 B2 D0 R0.0846 F6000\nG28\nG0 X70 Y45 F6000\n")

    pixels = list(img.getdata())
    pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
    forward = True

    #    def get_chunks(arr, chunk_size = 51):
    def get_chunks(arr, chunk_size=51):
        chunks = [
            arr[start:start + chunk_size]
            for start in range(0, len(arr), chunk_size)
        ]
        return chunks

#   return the last pixel that holds data.

    def last_in_list(arr):
        end = 0
        for i in range(len(arr)):
            if (arr[i] > 0):
                end = i

        return end

#   return the last pixel that holds data.

    def first_in_list(arr):
        end = 0
        for i in range(len(arr)):
            if (arr[i] == 0):
                end = i
            if (arr[i] > 0):
                break

        return end

    first = True
    row = pixels[::-1]

    previousRight = 99999999999
    previousLeft = 0
    firstRow = True

    for index, rowData in enumerate(row):
        print "Line " + str(index + 1) + " ="
        #print rowData

        splitRight = 0
        splitLeft = 0

        if (index + 1 < len(row)):
            # Determine where to split the lines.
            ##################################################

            #If the left most pixel of the next row is earlier than the current row, then extend.
            if (first_in_list(row[index + 1]) > first_in_list(rowData)):
                splitLeft = first_in_list(rowData)
            else:
                splitLeft = first_in_list(row[index + 1])

            #If the end pixel of the next line is later than the current line, extend.
            if (last_in_list(row[index + 1]) > last_in_list(rowData)):
                splitRight = last_in_list(row[index + 1])
            else:
                splitRight = last_in_list(rowData)

            print "Prior Left cut = " + str(
                splitLeft) + " Right Cut == " + str(splitRight)
        else:
            splitLeft = first_in_list(rowData)
            splitRight = last_in_list(rowData)

        #Positive direction
        if forward:
            print "Forward!"

            #Split the right side.
            ###########################################

            #Don't split more than the start of the last row as we print in reverse for alternate lines
            splitLeft = previousLeft
            previousRight = splitRight

        #Negative direction
        else:
            print "Backward!"

            #Split the left side.
            ###########################################

            #Don't split more than the end of the last row as we print in reverse for alternate lines
            splitRight = previousRight
            previousLeft = splitLeft

        #Exception to the rule : Don't split the left of the first row.
        if (firstRow):
            splitLeft = (previousLeft)

        firstRow = False
        print "After : Left cut = " + str(splitLeft) + " Right Cut == " + str(
            splitRight)

        row2 = rowData[(splitLeft + 1):(splitRight + 1)]
        print row2

        #if(index == 5):
        #    raise Exception('End')

        if not forward:
            result_row = row2[::-1]
        else:
            result_row = row2

        for chunk in get_chunks(result_row, 51):
            if first:
                if forward:
                    f.write("\nG7 $1 ")
#                    f.write("G7 $1\nG7 ")
                else:
                    f.write("\nG7 $0 ")


#                    f.write("G7 $0\nG7 ")
                first = not first
            else:
                f.write("G7 ")

            b64 = base64.b64encode("".join(chr(y) for y in chunk))
            f.write("L" + str(len(b64)) + " ")
            f.write("D" + b64 + "\n")
        forward = not forward
        first = not first

    f.write("M5 \n")
Exemplo n.º 50
0
 def decorated(image, *a, **kw):
     image = ImageOps.invert(image.convert("L"))
     applied = f(image, *a, **kw)
     return ImageOps.invert(applied)
Exemplo n.º 51
0
    return result


if __name__ == "__main__":
    results = []
    for file in input_files:

        # path = file
        im = Image.open(file)
        im = ImageOps.autocontrast(im)
        im = ImageOps.autocontrast(im)
        im = ImageOps.autocontrast(im)
        im = ImageOps.autocontrast(im)
        im = brighten(im, 2.1)
        im = ImageOps.grayscale(im)
        im = ImageOps.invert(im)
        im = im.point(lambda i: 250 if i > 1 else i)
        im = ImageOps.invert(im)
        im = clear_noise(im, 254, 1, 255)
        # im = im.convert("L")
        # im = polarize(im, 250)
        # im = clear_noise(im, 4, 1)
        # im = contrast(im, 2.0)
        path = tempfile.mktemp(dir="/tmp/mem/ems/") + ".png"

        im.save(path, "png")

        result = run_tesseract(path)
        result = post_process(result)
        results.append(result)
Exemplo n.º 52
0
    # further zoom on object to match scaling of archive images
    finderScale = idcScale / finderRatio
    w = img.size[0] * finderScale
    h = img.size[1] * finderScale
    scale = (int(w), int(h))
    img.resize(scale)

    # rotate the image according to the data, keep transparent background
    rot = img.rotate(-float(orientat), expand=1)
    img = Image.new("RGBA", rot.size, (255, 255, 255, 0))
    img.paste(rot, (0, 0), rot)

    # invert the full value scale and enable it as the alpha band
    alpha = img.convert("L")
    alpha = ImageOps.invert(alpha)
    img.putalpha(alpha)

    # turn the image to a yummy turquoise color
    img.paste((0, 133, 134), (0, 0), img)

    # save output file if non-existent
    if infile != outfile:
        try:
            img.save(outfile)
        except IOError:
            print "Cannot convert: " + infile
            iter += -1

# output success
print "You have successfully converted " + str(iter) + " files."
Exemplo n.º 53
0
    #text = r'$\sqrt{2}$'
    #text = r'$\sqrt[3]{x}$'
    
    box = parser.parse(text, fonts, 12, 72)
    width, height, descent = renderer.render(box)
    #svg.write()
    scale = 4.
    svg.set('width', scale*width)
    svg.set('height', scale*height)
    svg.set('transform', 'translate(0,%g) scale(%g)' % (height*scale - descent*scale,scale))
    show(svg, svg.width, svg.height)
    '''

    import Image, ImageOps

    parser = Parser()
    renderer = ImageBackend()
    fonts = BakomaFonts()

    #text = r'$\alpha > \beta$'
    #text = r'$\alpha_i > \beta_i$'
    text = r'$\sum_{i=0}^\infty x_i$'

    box = parser.parse(text, fonts, 64, 72)
    buffer = renderer.render(box)

    img = Image.fromstring('L', (buffer.width, buffer.height),
                           buffer.tobytes())
    img = ImageOps.invert(img)
    img.save('test.png')
Exemplo n.º 54
0
    for digit in range(0, 10):
        # Draw the digit on a large canvas so PIL doesn't crop it.
        scratch_canvas_image = Image.new("RGB", LARGE_SCRATCH_CANVAS_DIMENSIONS)
        draw = ImageDraw.Draw(scratch_canvas_image)

        draw.text((0,0), str(digit), font=font)

        # Discard all the padding
        cropped_digit_image = scratch_canvas_image.crop(scratch_canvas_image.getbbox())

        # Center the digit within the final image tile and save it
        digit_width, digit_height = cropped_digit_image.size

        tile_image = Image.new("RGB", FINAL_TILE_CANVAS_DIMENSIONS)

        tile_image.paste(cropped_digit_image, ((TILE_WIDTH_PIXELS-digit_width)/2, (TILE_HEIGHT_PIXELS-digit_height)/2))

        tile_image = ImageOps.invert(tile_image)

        tile_image.save(OUTPUT_IMAGE_FILEPATH_TEMPLATE % digit)

        meta_data_entries.append(META_DATA_TEMPLATE % (digit, digit))


    # Display the meta data which needs to be included in `resource_map.json`.
    print ",\n".join(meta_data_entries)




Exemplo n.º 55
0
 def operation(self, img):
     return ImageOps.invert(img)
Exemplo n.º 56
0
 def getBoxImage(self, image):
     invert_im = ImageOps.invert(image)
     return invert_im.getbbox()
Exemplo n.º 57
0
def cropBound(id):

    print 'cropBound', id
    maxBoundary = [1000, 1000, 0, 0]
    for k in range(0, 8):  #attack
        im = Image.open('ss' + str(id) + 'a' + str(k) + '.png')

        #需要使用两种技术分别 处理 图片的左右和上下空白
        #直接getbbox  做灰度图 之后 getbbox
        #nim = im.convert('L')
        #nim = ImageOps.invert(nim)
        #nim = nim.crop([1, 0]+list(nim.size))

        box = list(im.getbbox())
        size = im.size
        if box[2] == size[0] and box[3] == size[1]:
            print "notBox", id
            nim = im.convert('L')
            nim = ImageOps.invert(nim)
            nim = nim.crop([1, 0] + list(nim.size))
            box = list(nim.getbbox())

        print box, size
        midX = im.size[0] / 2
        difx = max(abs(box[0] - midX), abs(box[2] - midX))
        box[0] = midX - difx
        box[2] = midX + difx

        if box[0] < maxBoundary[0]:
            maxBoundary[0] = box[0]
        if box[1] < maxBoundary[1]:
            maxBoundary[1] = box[1]
        if box[2] > maxBoundary[2]:
            maxBoundary[2] = box[2]
        if box[3] > maxBoundary[3]:
            maxBoundary[3] = box[3]
    print id, 'a', maxBoundary
    res['a%d' % (id)] = maxBoundary
    for k in range(0, 8):
        im = Image.open('ss' + str(id) + 'a' + str(k) + '.png')
        nim = im.crop(maxBoundary)
        nim.save('ss' + str(id) + 'a' + str(k) + '.png')

    maxBoundary = [1000, 1000, 0, 0]
    for k in range(0, 7):  #move
        im = Image.open('ss' + str(id) + 'm' + str(k) + '.png')

        #nim = im.convert('L')
        #nim = ImageOps.invert(nim)
        #nim = nim.crop([1, 0]+list(nim.size))

        box = list(im.getbbox())

        size = im.size
        if box[2] == size[0] and box[3] == size[1]:
            print "notBox", id
            nim = im.convert('L')
            nim = ImageOps.invert(nim)
            nim = nim.crop([1, 0] + list(nim.size))
            box = list(nim.getbbox())
        print box, size

        midX = im.size[0] / 2
        difx = max(abs(box[0] - midX), abs(box[2] - midX))
        box[0] = midX - difx
        box[2] = midX + difx

        if box[0] < maxBoundary[0]:
            maxBoundary[0] = box[0]
        if box[1] < maxBoundary[1]:
            maxBoundary[1] = box[1]
        if box[2] > maxBoundary[2]:
            maxBoundary[2] = box[2]
        if box[3] > maxBoundary[3]:
            maxBoundary[3] = box[3]
    print id, 'm', maxBoundary
    res['m%d' % (id)] = maxBoundary
    for k in range(0, 7):
        im = Image.open('ss' + str(id) + 'm' + str(k) + '.png')
        nim = im.crop(maxBoundary)
        nim.save('ss' + str(id) + 'm' + str(k) + '.png')