Example #1
0
def display_bounding_boxes(img,
                           blocks,
                           alternatecolors=False,
                           color=Color("blue")):
    """
    Displays each of the bounding boxes passed in 'boxes' on an image of the pdf
    pointed to by pdf_file
    boxes is a list of 5-tuples (page, top, left, bottom, right)
    """
    draw = Drawing()
    draw.fill_color = Color("rgba(0, 0, 0, 0)")
    draw.stroke_color = color
    for block in blocks:
        top, left, bottom, right = block[-4:]
        if alternatecolors:
            draw.stroke_color = Color("rgba({},{},{}, 1)".format(
                str(np.random.randint(255)),
                str(np.random.randint(255)),
                str(np.random.randint(255)),
            ))
        draw.rectangle(left=float(left),
                       top=float(top),
                       right=float(right),
                       bottom=float(bottom))
        draw(img)
    display(img)
 def draw_text(self,
               image,
               x,
               y,
               text,
               font_size=15,
               font_style='normal',
               font=None,
               text_alignment='left',
               text_color='Black',
               filename=None,
               is_display=False):
     draw = Drawing()
     print('draw text={} in x={}, y={}'.format(text, x, y))
     if font is not None:
         draw.font = font
     draw.fill_color = Color(text_color)
     draw.font_size = font_size
     draw.font_style = font_style
     draw.text_alignment = text_alignment
     draw.text(x, y, text)
     draw(image)
     if is_display:
         display(image)
     if filename is not None:
         image.save(filename=filename)
     return image
Example #3
0
def wand1():
    """This is Python Wand example 1"""
    the_time = t.asctime()

    print "Importing image ", IFILE
    img_1 = Image(filename=IFILE)

    print "Cropping and resizing the image"
    img_1.crop(300, 0, width=300, height=282)
    img_1.resize(width=600, height=564)

    print "Creating a drawing and overlaying on it"
    draw = Drawing()

    draw.circle((100, 100), (120, 120))

    draw.rectangle(left=img_1.width-300, top=img_1.height-45, width=230,
               height=40, radius=5)

    draw.font_size = 17
    draw.fill_color = Color('white')
    draw.text_color = Color('white')
    draw.text(img_1.width-290, img_1.height-20, the_time)
    draw(img_1)

    print "Displaying, close the XTERM when done"
    display(img_1)
Example #4
0
def main():
	with (
		wand.image.Image(filename='thisyouradmin1.png') as this_your_admin,
		wand.image.Image(filename='thisyouradmin2.png') as you_clowns,
		wand.image.Image(blob=sys.stdin.buffer.read()) as to_insert,
	):
		target_width = this_your_admin.width - 2 * POST_PADDING - 2 * IMAGE_PADDING
		to_insert.transform(resize=f'{target_width}x{to_insert.height}')

		# lol i don't wanna indent for another context manager
		out = wand.image.Image(
			width=this_your_admin.width,
			height=this_your_admin.height + to_insert.height + you_clowns.height,
		)
		out.composite(this_your_admin, 0, 0)

		draw_background(
			out, color=PAGE_BACKGROUND_COLOR,
			left=0, top=this_your_admin.height,
			right=out.width, bottom=this_your_admin.height+to_insert.height,
		)

		draw_background(
			out, color=POST_BACKGROUND_COLOR,
			left=POST_PADDING, top=this_your_admin.height,
			right=out.width-POST_PADDING, bottom=this_your_admin.height+to_insert.height,
		)

		out.composite(to_insert, POST_PADDING + IMAGE_PADDING, this_your_admin.height)
		out.composite(you_clowns, 0, this_your_admin.height + to_insert.height)
		with out.convert('png') as out:
			out.save(file=sys.stdout.buffer)
			display(out)
Example #5
0
 def display(self, filename='out.bmp'):
     self.write(filename)
     try:
         from wand.image import Image
         from wand.display import display
         with Image(filename=filename) as image:
             display(image)
     except ImportError:
         pass
Example #6
0
def main():
    funky_img = Image(filename="../images/funky_illustration.png")
    funky_img = resize_to_percent(funky_img, 60)

    cropped_img = funky_img.clone()
    cropped_img.crop(top=0, left=275, width=340, height=486)

    display(funky_img)
    display(cropped_img)
Example #7
0
def image_show_im():  # ImageMagickを使ってイメージを表示
    from wand.image import Image
    from wand.display import display

    img = Image(filename='oreilly_im.png')  # oreilly.pngを読み込み
    print(img.size)     # サイズを表示
    print(img.format)   # フォーマットを表示

    display(img)
Example #8
0
    def glFinish(self, filename='out.bmp'):
        self.write(filename)
        try:
            from wand.image import Image
            from wand.display import display

            with Image(filename=filename) as image:
                display(image)
        except ImportError:
            pass  # do nothing if no wand is installed
def resize_and_rotate(filename, resize_ratio, rotate_angle, target):
    with Image(filename=filename) as img:
        print('original size', img.size)
        names = os.path.splitext(target)
        save_name = names[0] + '_%d' + names[1]
        for r in range(1, 4):
            with img.clone() as i:
                i.resize(int(i.width * resize_ratio * r), int(i.height * resize_ratio * r))
                i.rotate(rotate_angle * r)
                i.save(filename=save_name % r)
                display(i)
  def display(self, filename='out.bmp'):
    """
    Displays the image, a external library (wand) is used, but only for convenience during development
    """
    self.write(filename)

    from wand.image import Image
    from wand.display import display

    with Image(filename=filename) as image:
      display(image)
Example #11
0
def main():
    req_width = 595
    req_height = 486
    baby_img = Image(filename="baby_cc_sh.png")
    baby_img = resize_to_height(baby_img, req_height)

    baby_img.flop()

    full_img = new_blank_png(req_width, req_height)
    full_img.composite(baby_img, 0, 0)

    display(full_img)
Example #12
0
    def display(self, name='out'):
        self.glFinish(name)

        try:
            from wand.image import Image
            from wand.display import display

            with Image(filename=name + '.bmp') as image:
                display(image)
        except Exception as e:
            print(e)
            pass  # do nothing if no wand is installed
Example #13
0
 def tweetgen(self, verified=False, debug=False):
     avatar = self.create_circular_image(self.avatar)
     reply = self.create_icon("\uf151",
                              fg=self.theme["icon_color"],
                              bg="transparent",
                              size=20)
     retweet = self.create_icon("\uf152",
                                fg=self.theme["icon_color"],
                                bg="transparent",
                                size=20)
     if verified:
         verified = self.create_icon(
             "\uF099",
             fg=self.theme["verified_icon_color"],
             bg="transparent",
             size=16,
         )
     like = self.create_icon("\uf148",
                             fg=self.theme["icon_color"],
                             bg="transparent",
                             size=20)
     name = self.create_text(self.name,
                             fg=self.theme["name_color"],
                             bg="transparent",
                             weight=600)
     handle = self.create_text(f"@{self.handle}",
                               fg=self.theme["handle_color"],
                               bg="transparent")
     text = self.create_text(self.text,
                             fg=self.theme["text_color"],
                             bg="transparent")
     twidth, theight = text.width, text.height
     twidth = twidth + 130 if twidth > 200 else 330
     with Image(width=twidth,
                height=150,
                background=Color(self.theme["background_color"])) as tweet:
         tweet.format = "png"
         tweet.composite(avatar, left=10, top=20)
         tweet.composite(name, left=120, top=20)
         name_header = 120
         if verified:
             name_header = 138
             tweet.composite(verified, left=name.width + 120, top=20)
         tweet.composite(handle, left=name.width + name_header, top=21)
         tweet.composite(text, left=120, top=42)
         button_height = theight + 50
         tweet.composite(reply, left=120, top=button_height)
         tweet.composite(retweet, left=200, top=button_height)
         tweet.composite(like, left=280, top=button_height)
         if debug:
             display(tweet)
         return BytesIO(tweet.make_blob())
def main():
    #
    # initial greeting...
    #
    print("Hello Google Cloud Storage!")
    #
    # create a client
    #
    print("creating client...")
    client = storage.Client()
    index = 0
    print("indexing over bucket list...")
    for bucket in client.list_buckets():
        print(bucket)
        print("index = " + str(index))
        if index == 0:
            defaultBucket = bucket
        index += 1
    print("")
    print("chosen bucket is: " + str(defaultBucket))
    blob = Blob("raw_image.jpg", defaultBucket)
    quit = False
    imageFilePath = "/home/shawn/Desktop/raw_image_download.jpg"
    while quit == False:
        blobCount = 0
        for blobItem in defaultBucket.list_blobs():
            blobCount += 1
        if blobCount == 0:
            print("empty...")
        else:
            print("downloading...")
            with open(imageFilePath, "wb") as imageFile:
                blob.download_to_file(imageFile)
            with Image(filename=imageFilePath) as img:
                print(img.size)
                print("blurring...")
                img.gaussian_blur(9, 1)
                imageFilePath = "/home/shawn/Desktop/blurred_image.jpg"
                print("saving...")
                img.save(filename=imageFilePath)
            with Image(filename=imageFilePath) as img:
                blob = Blob("blurred_image.jpg", defaultBucket)
                print("uploading...")
                with open("/home/shawn/Desktop/blurred_image.jpg",
                          "rb") as imageFile:
                    blob.upload_from_file(imageFile)
                display(img)
        time.sleep(1.0)
    #
    # final greeting...
    #
    print("Goodbye Google Cloud Storage!")
Example #15
0
    def display(self, filename='out.bmp'):
        """
    Displays the image, a external library (wand) is used, but only for convenience during development
    """
        self.write(filename)

        try:
            from wand.image import Image
            from wand.display import display

            with Image(filename=filename) as image:
                display(image)
        except ImportError:
            pass  # do nothing if no wand is installed
def convert_pdf(input_path, output_path, threshold=0.47):
    print('Reading file...')
    with Image(filename=input_path, resolution=300) as pdf_input, Image() as pdf_output:
        print('Opened {} with {} pages.'.format(input_path, len(pdf_input.sequence)))
        for i, page in enumerate(pdf_input.sequence):
            print('Processing page {} of {}...'.format(i + 1, len(pdf_input.sequence)))
            with Image(page) as img:
                img.threshold(threshold=threshold, channel='red')
                img.threshold(threshold=threshold, channel='green')
                img.threshold(threshold=threshold, channel='blue')
                pdf_output.sequence.extend([img])
                display(img)

        print('Writing to {}...'.format(output_path))
        pdf_output.save(filename=output_path)
 def composite(self, img_back, img, left, top, save_name=None):
     with Image(filename=img_back) as w:
         with Image(filename=img) as r:
             with Drawing() as draw:
                 draw.composite(operator='atop',
                                left=left,
                                top=top,
                                width=r.width,
                                height=r.height,
                                image=r)
                 draw(w)
                 display(w)
                 if save_name is not None:
                     w.save(filename=save_name)
     return w
def output_image(colors, filename):
    width = 800
    height = 600
    color_width = 100
    color_height = 60

    with Drawing() as draw:
        draw.stroke_color = Color("black")
        for i, color in enumerate(colors):
            draw.fill_color = Color(color['exact'])
            draw.rectangle(
                left=(width - color_width * 2),
                top=color_height * i,
                width=color_width,
                height=color_height)
            draw.fill_color = Color(color['near'])
            draw.rectangle(
                left=width - color_width,
                top=color_height * i,
                width=color_width,
                height=color_height)
            t = color['near'] + " - %d%%" % int(color['percent'] * 100)
            draw.text(
                width - (color_width),
                (color_height * i) + (color_height / 2),
                t)

        with Image(
            width=width,
            height=height,
            background=Color('white')
        ) as img:
            i = Image(filename=args['image'])
            i_width = width - (color_width * 2)
            i_height = i.height / (float(i.width) / i_width)
            draw.composite(
                operator='over',
                left=0,
                top=0,
                width=i_width,
                height=i_height,
                image=i)

            draw.draw(img)
            if filename == 'display':
                display(img)
            else:
                img.save(filename=filename)
Example #19
0
 def display_candidates(self, tree, html_path, filename_prefix):
     """
     Displays the bounding boxes corresponding to candidates on an image of the pdf
     boxes is a list of 5-tuples (page, top, left, bottom, right)
     """
     imgs = self.display_boxes(tree,
                               html_path,
                               filename_prefix,
                               alternate_colors=True)
     return display(*imgs)
Example #20
0
def combine_images(*images: List[Union[str, bytes, WandImage]]) -> Image:
    with ThreadPool() as pool:
        images = pool.map(normalize_image, images)

    max_width = round(mean(img.width for img in images))
    max_height = round(mean(img.height for img in images))
    sum_width = max_width * len(images)

    canvas = WandImage(width=sum_width, height=max_height)
    resizer = ImageResizer(max_width, max_height)

    left = 0
    draw = Drawing()
    draw.fill_color = Color('white')
    draw.rectangle(left=0, top=0, right=canvas.width, bottom=canvas.height)
    draw(canvas)

    for img in images:
        if img.height < max_height:
            img = resizer.resize(img, max_height / img.height)

        if img.width < max_width:
            img = resizer.resize(img, max_width / img.width)
        elif img.width > max_width:
            # Do a bit of cropping so it's centered
            crop_left = round((img.width - max_width) / 2)
            crop_right = crop_left + max_width
            img.crop(crop_left, 0, crop_right, img.height)

        draw.composite(operator='over',
                       top=0, left=left,
                       width=img.width, height=img.height,
                       image=img)
        draw(canvas)
        left += img.width

    if DEBUG_IMAGE:  # pragma: no cover
        server_name = os.environ.get('DISPLAY', ':0')
        display(canvas, server_name=server_name)

    return Image(content=canvas.make_blob(format='png'),
                 content_type='image/png')
 def composite_with_image(self,
                          img_back,
                          img,
                          left,
                          top,
                          save_name=None,
                          is_display=False):
     draw = Drawing()
     draw.composite(operator='atop',
                    left=left,
                    top=top,
                    width=img.width,
                    height=img.height,
                    image=img)
     draw(img_back)
     if is_display:
         display(img_back)
     if save_name is not None:
         img_back.save(filename=save_name)
     return img_back
def make_crops(filename, faces, margin):
    result = {"faces": copy.deepcopy(faces)}

    images_dir = os.path.dirname(filename)

    with io.open(filename, 'rb') as image_file:
        with Image(file=image_file) as img:
            width = img.width
            height = img.height
            print "Original image size {}x{}".format(width, height)
            result["resolution"] = {"x": width, "y": height}
            result["filename"] = os.path.basename(filename)

            print "Loop over faces"
            for i, face in enumerate(result["faces"]):

                this_margin = margin

                bounds = get_bounds(face)

                bounds = pad_bounds(bounds, (width, height), margin)

                minx, miny, maxx, maxy = bounds

                print "Crop is top-left:{},{} - bottom-right:{},{}".format(
                    minx, maxx, miny, maxy)
                with img[minx:maxx, miny:maxy] as cropped:
                    # root, ext = os.path.splitext(filename)
                    face["filename"] = "face_{}.png".format(i)
                    print "Cropped filename is:", face["filename"]
                    cropped.format = 'png'
                    cropped.save(
                        filename=os.path.join(images_dir, face["filename"]))
                    face["crop"] = {
                        "minx": minx,
                        "miny": miny,
                        "maxx": maxx,
                        "maxy": maxy
                    }
                    display(cropped)
    return result
Example #23
0
def main():
    req_width = 595
    req_height = 486
    baby_img = Image(filename="baby_cc_sh.png")
    baby_img = resize_to_height(baby_img, req_height)

    temp_img = new_blank_png(req_width, req_height)
    temp_img.composite(baby_img, 0, 0)
    baby_img = temp_img

    mask_img = new_blank_png(req_width, req_height, color=Color('rgb(32,32,32)'))
    mask_img.save(filename="mask_img.png")

    print "DEBUG baby_img", baby_img.alpha_channel
    print "DEBUG mask_img", mask_img.alpha_channel

    baby_img_masked = baby_img.clone()
    baby_img_masked.composite_channel(channel='all_channels', image=mask_img, operator='copy_opacity')

    display(baby_img)
    display(baby_img_masked)

    baby_img.save(filename="baby_img.png")
    baby_img_masked.save(filename="baby_img_masked.png")
Example #24
0
    with Drawing() as context:
        context.font = font_text
        context.fill_color = Color('#FF9999')
        context.font_size = 150
        #metrics = context.get_font_metrics(img_background, body_text, multiline=True)
        body_text = "DAWONG"
        context.text(x=150, y=400, body=body_text)
        context(img_background)
        metrics = context.get_font_metrics(img_background,
                                           body_text,
                                           multiline=True)
        print(metrics)

    # with Drawing() as context:
    #     context.font = font_text
    #     context.fill_color = Color('#00FF80')
    #     context.font_size = 300
    #     #metrics = context.get_font_metrics(img_background, body_text, multiline=True)
    #     context.text(
    #         x=750,
    #         y=1450,
    #         body="2")
    #     context(img_background)
    # with Image(filename=filename_logo) as logo_liverpool:
    #     img_background.composite(logo_liverpool, left=180, top=1200)
    # with Image(filename=filename_logo1) as logo_totenham:
    #     logo_totenham.resize(400,400)
    #     img_background.composite(logo_totenham, left=110, top=600)
    display(img_background)
    img_background.format = "png"
    img_background.save(filename=filename_output)
Example #25
0
 def show(self):
     return display(image=self._im)
from PIL import Image
from wand.image import Image as wImage
from wand.display import display
from StringIO import StringIO
from PIL.PngImagePlugin import PngImageFile
import iconfile

pin = iconfile.pinIcon.GetData()
wim = wImage(blob=pin)
display(wim)
im = Image.open("c:\p.png")
#help(im)
if isinstance(im, PngImageFile):
    print "pil instance"
fil = StringIO()
im.save(fil, 'PNG')
wim = wImage(blob=fil.getvalue())
help(wim)
if isinstance(wim, wImage):
    print "wim"
fil.close()
#display(wim)
fil2 = StringIO()
wim.save(fil2)
im2 = Image.open(StringIO(fil2.getvalue()))
im2.save("c:\\test2.png")
Example #27
0
from wand.image import Image
from wand.display import display

with Image(filename='omelet.jpg') as img:
    print img.size
    for r in 1, 2, 3:
        with img.clone() as i:
            i.resize(int(i.width * r * 0.25), int(i.height * r * 0.25))
            i.rotate(90 * r)
            i.save(filename='omelet-{0}.jpg'.format(r))
            display(i)
Example #28
0
 def __call__(self, *args, **kwargs):
     display(
         Image(filename=os.path.expanduser(
             '~/Pictures/memes?/my-number-iphone.png')))
import urllib2
import random

from wand.image import Image
from wand.display import display


fg_url = fg_url = 'http://emojidictionary.emojifoundation.com/img/emoji{}.jpg'.format(random.randint(1, 800)) #random emoji
bg_url = 'http://bit.ly/2ewFjd5'

bg = urllib2.urlopen(bg_url)
with Image(file=bg) as bg_img:
    fg = urllib2.urlopen(fg_url)
    with Image(file=fg) as fg_img:
        bg_img.composite(fg_img, left=214, top=160)
    fg.close()
    display(bg_img)
bg.close()
Example #30
0
    # Open red_channel_image
    with Image(filename=args.red_channel_image) as red:
        if args.verbose:
            print args.red_channel_image
            for key, value in green.metadata.items():
                print(key, value)

        # Clone green_channel_image to "result" to ensure we're non-destructive
        with green.clone() as result:
            # Receive only the red channel from red_channel_image onto result
            result.composite_channel(
                channel='all_channels',
                image=red,
                operator='copy_red')

            # Remove blue channel from result by compositing it with a minus
            # operation onto final
            with result.clone() as final:
                final.composite_channel(
                    channel='blue',
                    image=result,
                    operator='minus')

                if args.preview:
                    display(final)
                else:
                    final.save(filename=outfile)
                    if args.verbose:
                        print "Composite image saved to", outfile
Example #31
0
    o = original.orientation
    print o
    if o in orientation:
        with original.convert("png") as image:
            with image.clone() as img:
                if o == "top_right":
                    img.flop()
                    img.save(filename="out/%s-img.jpg" % o)
                elif o == "bottom_right":
                    img.rotate(180)
                    img.save(filename="out/%s-img.jpg" % o)
                elif o == "bottom_left":
                    img.flip()
                    img.save(filename="out/%s-img.jpg" % o)
                elif o == "left_top":
                    img.rotate(90)
                    img.flop()
                    img.save(filename="out/%s-img.jpg" % o)
                elif o == "right_top":
                    img.rotate(90)
                    img.save(filename="out/%s-img.png" % o)
                elif o == "right_bottom":
                    img.rotate(-90)
                    img.flop()
                    img.save(filename="out/%s-img.jpg" % o)
                elif o == "left_bottom":
                    img.rotate(-90)
                    img.save(filename="out/%s-img.jpg" % o)

                display(img)
   source_path=("pict/20140905002012_0.jpg",
             "pict/20140905002012_1.jpg",
             "pict/20140905002012_2.jpg",
             "pict/20140905002012_3.jpg")
   output_path="inter/20140905002012.jpg"
   img_4to1(source_path, output_path)


   #img_h_flip test code
   img_h_flip("Mask/1_0_hor.png","result/flop.jpg")
   img_v_flip("Mask/1_0_hor.png","result/flip.jpg")
    

   with Image(filename='foo.jpg') as img:
      print(img.size)
      img.format='jpeg'
      display(img)
   with Image(filename='overlay.png') as overlay:
      overlay.flop()
      display(overlay)
      img.composite(overlay,0,0)
      display(img)
      img.save(filename='output.jpg')


   #require a horizonal flop funtion
   #require a simple overlay (1 on 1)
   #require a function to merge 4 pic into 1

    
Example #33
0
mustache = Image.open('moustaches.png')
handlebar = mustache.crop((316, 282, 394, 310))
handlebar.size

img.paste(handlebar, (45, 90))
img.show()

from wand.image import Image
from wand.display import display

img = Image(filename='oreilly.png')
img.size

img.format

display(img)

import tkinter
from PIL import Image, ImageTk

main = tkinter.Tk()
img = Image.open('oreilly.png')
tkimg = ImageTk.PhotoImage(img)
tkinter.Label(main, image=tkimg).pack()
main.mainloop()

import matplotlib.pyplot as plot
import matplotlib.image as image

img = image.imread('oreilly.png')
plot.imshow(img)
Example #34
0
 def display(self):
     display(self.canvas)
    def add_char(self, char):
        if char in self.chars:
            print("Char {} already exists!".format(c))
            return
        with Drawing() as draw:
            draw.font = self.font
            draw.font_size = self.fontsize
            draw.text_antialias = self.antialias
            draw.text_resolution = 72  # point==pixel

            metrics = draw.get_font_metrics(self.dummy_img, char)
            if self.lineheight == None:
                self.lineheight = int(
                    ceil(metrics.ascender - metrics.descender))
                self.ascender = int(ceil(metrics.ascender))
                self.descender = int(ceil(metrics.descender))
            #if self.charwidth < metrics.character_width :
            #	self.charwidth = int(ceil(metrics.character_width))
            if self.charwidth < metrics.text_width:
                self.charwidth = int(ceil(metrics.text_width))

            drop_char = False
            data_idx = -1
            if char == ' ':
                x1 = x2 = y1 = y2 = 0
            else:
                # TODO start using the bbox (have to figure out how it works first!)
                x1 = int(round(metrics.x1))
                x2 = int(round(metrics.x2))
                y1 = int(round(metrics.y1))
                y2 = int(round(metrics.y2))
                w = int(ceil(metrics.text_width))
                h = int(ceil(metrics.text_height))
                spatzig = 1
                w += 2 * spatzig
                x1 -= spatzig
                x2 += spatzig
                h += 2 * spatzig
                y1 -= spatzig
                y2 += spatzig
                # try to align bbox to size..
                while x2 - x1 > w:
                    w += 1
                    if x2 - x1 == w: break
                    w += 2
                    x1 += 1
                    #if x2-x1 == w : break
                    #x2 -= 1
                while x2 - x1 < w:
                    x1 -= 1
                    if x2 - x1 == w: break
                    x2 += 1
                while y2 - y1 > h:
                    h += 1
                    if y2 - y1 == h: break
                    h += 2
                    y1 += 1
                    #if y2-y1 == h : break
                    #y2 -= 1
                while y2 - y1 < h:
                    y1 -= 1
                    if y2 - y1 == h: break
                    y2 += 1

                #with Image(width=x2-x1, height=y2-y1, background=Color('black')) as img:
                with Image(width=w, height=h,
                           background=Color('black')) as img:
                    draw.push()
                    draw.fill_color = Color('white')
                    draw.text(1, 1 + int(round(metrics.ascender)), char)
                    draw.pop()
                    draw(img)
                    #display(img)
                    d = np.frombuffer(img.make_blob("RGB"),
                                      dtype=[
                                          ('r', np.uint8), ('g', np.uint8),
                                          ('b', np.uint8)
                                      ])['r'].reshape(img.height, img.width)
                    #d = d[y1:,x1:]

                    if (d == 0).all():
                        if char == "_":
                            draw.stroke_color = Color('white')
                            draw.stroke_width = 1
                            y = int(metrics.ascender + 1)
                            #print((w,h),(x1+1, y), (x2-1,y))
                            #draw.line((x1+1, y), (x2-1,y))
                            draw.line((1, y), (w - 1, y))
                            draw(img)
                            display(img)
                            d = np.frombuffer(img.make_blob("RGB"),
                                              dtype=[('r', np.uint8),
                                                     ('g', np.uint8),
                                                     ('b', np.uint8)
                                                     ])['r'].reshape(
                                                         img.height, img.width)
                            drop_char = (d == 0).all()
                        else:
                            drop_char = True

                    if not drop_char:
                        x1 = y1 = -spatzig
                        x2 = w - spatzig
                        y2 = h - spatzig

                        # crop
                        for y in range(0, d.shape[0]):
                            if not (d[y, :] == 0).all():
                                if y > 0: d = d[y:, :]
                                break
                            y1 += 1
                        for y in range(d.shape[0] - 1, 0 - 1, -1):
                            if not (d[y, :] == 0).all():
                                d = d[:y + 1, :]
                                break
                            y2 -= 1
                        for x in range(0, d.shape[1]):
                            if not (d[:, x] == 0).all():
                                if x > 0: d = d[:, x:]
                                break
                            x1 += 1
                        for x in range(d.shape[1] - 1, 0 - 1, -1):
                            if not (d[:, x] == 0).all():
                                d = d[:, :x + 1]
                                break
                            x2 -= 1

                        d, x1, x2, y1, y2 = self.fix_data_size_and_bbox(
                            d, x1, x2, y1, y2)

                        for i in range(0, len(self.chars_data)):
                            #print("######################################\n",d.shape,"\n",self.chars_data[i].shape)
                            #print(d,"\n",self.chars_data[i])
                            if (d.shape
                                    == self.chars_data[i].shape) and np.all(
                                        d == self.chars_data[i]):
                                data_idx = i
                                break
                            from time import sleep

                        if data_idx == -1:
                            data_idx = len(self.chars_data)
                            self.chars_data.append(d)
            if drop_char:
                print("\b!>{}<!".format(char), end='')
            else:
                self.chars[char] = {
                    'bbox': (x1, y1, x2, y2),
                    'data_idx': data_idx
                }
Example #36
0
    def processStatus(self, status):
        log("Received message <{0}> from @{1}".format(status.text, status.author.screen_name), self.twitterAPI.api.me().screen_name)

        # Detect file in tweet
        if "media" in status.entities:
            req = urlopen(status.entities["media"][0]["media_url_https"])
            arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
            img = cv2.imdecode(arr, -1)  # 'load it as it is'
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = self.faceCascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30)
                # flags = cv2.CV_HAAR_SCALE_IMAGE
            )
            req.close()
            temp = tempfile.TemporaryFile()
            if len(faces) >= 1:
                req = urlopen(status.entities["media"][0]["media_url_https"])
                with Image(file=req) as bg_img:
                    with Image(filename='asunaxan.png') as waifu:
                        bg_img.composite(waifu, left=faces[0][0]+40, top=faces[0][1]+20)

                        temp = tempfile.TemporaryFile()
                        temp.write(bg_img.make_blob(format="jpeg"))
                        temp.seek(0)

                        self.twitterAPI.api.update_with_media("Example.jpg", status="@{0} ojalá tú y yo juntos bb".format(self.boyfriendNEW.twitter.screen_name), file=temp, in_reply_to_status_id=status.id)

                        temp.close()

                    # draw(w)
                    display(bg_img)
                req.close()

        # Check for mention
        elif "@"+self.me.upper() in status.text.upper():
            if status.author.id == self.boyfriendNEW.twitter.id:
                if "¿Qué temperatura hay?" in status.text and (self.forecast.limit - self.forecast.current) > 0:
                    message = "Ahora mismo hay {0}ºC en tu zona".format(self.forecast.getForecast(self.boyfriendNEW.city).currently().temperature)
                    self.answer(message, status, status.user.screen_name)
                elif "holi" in status.text.lower():
                    message = "Holaaaa mi amooor {0}".format(self.getRandomWord(self.happyExpressions))
                    self.answer(message, status, status.user.screen_name)
                elif "quien es tu senpai" in status.text.lower():
                    message = "Tu eres mi senpai {0}".format(self.getRandomWord(self.happyExpressions))
                    self.answer(message, status, status.user.screen_name)
                elif "donde estoy" in status.text.lower():
                    if status.place != None:
                        place = status.place.full_name
                        message = "Ahora mismo te encuentras en {0}".format(place)
                    else:
                        message = "Lo siento, pero no dispongo de datos de geolocalizacion"
                    self.answer(message, status, status.user.screen_name)
                elif "recomiendame un anime" in status.text.lower():
                    log("Buscando un anime", self.me)
                    params = urlencode({'client': "watashiwaifu", 'clientver': 1, 'protover': 1, "request": "hotanime"})
                    url = "http://api.anidb.net:9001/httpapi?%s" % params
                    request = Request(url, None, FAKE_HEADERS)
                    with contextlib.closing(urlopen(request)) as response:
                        if response.info().get('Content-Encoding') == 'gzip':
                            buf = BytesIO(response.read())
                            f = gzip.GzipFile(fileobj=buf)
                            data = f.read()
                        else:
                            data = response.read()
                        root = ElementTree.XML(data)
                        animes = root.findall("anime")
                        rand = random.randint(0, len(animes)-1)
                        anime = animes[rand]
                        rank = ""
                        name = ""

                        for title in anime.findall("title"):
                            name = title.text
                        for picture in anime.findall("picture"):
                            photo = "http://img7.anidb.net/pics/anime/" + picture.text
                            portada = urlopen(photo).read()
                        for rating in anime.findall("ratings"):
                            for temporary in rating.findall("temporary"):
                                rank = temporary.text

                        temp = tempfile.TemporaryFile()
                        temp.write(portada)
                        temp.seek(0)
                        self.twitterAPI.api.update_with_media("Example.jpg", status="@{0} {1} {2}/10".format(status.author.screen_name, name, rank), file=temp, in_reply_to_status_id=status.id)
                        temp.close()
                else:
                    message = "Lo siento, no entiendo lo que me pides {0}".format(self.getRandomWord(self.sadExpressions))
                    self.answer(message, status, status.user.screen_name)
            else:
                message = "¿Tú qué haces hablandome? {0}".format(self.getRandomWord(self.angryExpressions))
                self.answer(message, status, status.user.screen_name)
with Image(filename='bob.png') as img:

    print(img.size)

    for r in 1, 2, 3:

        with img.clone() as i:

            i.resize(int(i.width * r * 0.25), int(i.height * r * 0.25))

            i.rotate(90 * r)

            i.save(filename='bob-{0}.png'.format(r))

            display(i)

# windows to display image

cv2.namedWindow("Image")

image = cv2.imread('bob.png')

h, w = image.shape[:2]

print h, w

# show image

cv2.imshow("Image", image)