Exemplo n.º 1
0
def remove_background(filename):
    """ Remove the background of the image in 'filename' """
    img = pg.Image(filename)
    transmask = trans_mask_sobel(img)
    img = alphacomposite(transmask, img)
    img.trim()
    img.write('out.png')
Exemplo n.º 2
0
def pgmagick_scale_plus_sharpen(filename, width, height):
    im = pgmagick.Image(pgmagick.Blob(open(filename).read()),
                        pgmagick.Geometry(width, height))
    im.scale('%dx%d' % (width, height))
    im.sharpen(1)
    im.quality(95)
    im.write('outpgsharpen.jpg')
Exemplo n.º 3
0
def alpha_composite(image, mask):
    """ Composite two images together by overriding one opacity channel """

    compos = pg.Image(mask)
    compos.composite(image, image.size(),
                     pg.CompositeOperator.CopyOpacityCompositeOp)
    return compos
Exemplo n.º 4
0
def pyimlib2_scale_with_pgmagicksharpen(filename, width, height):
    im = pyimlib2.open(filename)
    newim = im.scaled_image(width, height)
    newim.save('outpyimlib2.jpg', 'jpeg', 95)
    im = pgmagick.Image('outpyimlib2.jpg')
    im.sharpen(1)
    im.write('outpyimlib2_with_sharpen.jpg')
Exemplo n.º 5
0
def wand_image_extractor(filename, isMask=False,args=None):
    import pgmagick
    im = pgmagick.Image(filename)
    myPilImage = Image.new('RGB', (im.GetWidth(), im.GetHeight()))
    myPilImage.fromstring(im.GetData())
    return ImageWrapper(np.asarray(myPilImage), mode=myPilImage.mode, info=myPilImage.info,
                        to_mask=isMask,
                        filename=filename)
Exemplo n.º 6
0
def remove_background():

    img = pg.Image('shoe-1.png')
    transmask = trans_mask_sobel(img)
    img = alpha_composite(transmask, img)
    img.write('alpha-composite.png')
    img.trim()
    img.write('out-1.jpg')
Exemplo n.º 7
0
 def __init__(self, filename=None, color=None, *args, **kargs):
     self.img = None
     if sys.version_info >= (3, ) and isinstance(filename, (str)):
         self.img = pgmagick.Image(str(filename))
     elif sys.version_info < (3, ) and isinstance(filename, (unicode, str)):
         self.img = pgmagick.Image(str(filename))
     elif isinstance(filename, (list, tuple)):
         size = filename
         geometry = pgmagick.Geometry(int(size[0]), int(size[1]))
         if isinstance(color, (list, tuple)):
             r, g, b = int(color[0]), int(color[1]), int(color[2])
             color = pgmagick.Color(r, g, b)
             self.img = pgmagick.Image(geometry, color)
         elif isinstance(color, str):
             if color.find('gradient') == 0 or color.find('plasma') == 0:
                 self.img = pgmagick.Image(geometry, pgmagick.Color())
                 self.img.read(color)
             else:
                 color = pgmagick.Color(color)
                 self.img = pgmagick.Image(geometry, color)
         else:
             self.img = pgmagick.Image(geometry, pgmagick.Color())
         self.img.write(pgmagick.Blob(), 'MIFF')
     else:
         self.img = pgmagick.Image()
Exemplo n.º 8
0
def alpha_composite(image, mask):

    compos = pg.Image(mask)
    compos.composite(
        image,
        image.size(),
        pg.CompositeOperator.CopyOpacityCompositeOp
    )
    return compos
Exemplo n.º 9
0
def remove_background(filepath):
    """ Remove the background of the image in 'filename' """

    img = pg.Image(filepath)
    transmask = trans_mask_sobel(img)
    img = alpha_composite(transmask, img)
    img.trim()
    path = 'out.png'
    img.write(path)
    return path
Exemplo n.º 10
0
 def _pgmagick(self):
     '''When an error is encountered while opening an image, run
     it through pgmagick since it is a lot more forgiving of errors
     (truncation, bad headers, etc). This seems to be rare, but this
     way we can process more things successfully. We want to still
     use PIL for all other operations we perform since they are faster
     than pgmagick.'''
     if self._pgmagick_ran:
         raise BadImage(_('Already converted with pgmagick'))
     self._pgmagick_ran = True
     blob = pgmagick.Blob(self.raw)
     image = pgmagick.Image()
     image.ping(blob)
     self._check_info(
         dict(format=image.magick(),
              width=image.columns(),
              height=image.rows()))
     image = pgmagick.Image(blob)
     image.quality(self.config['quality'])
     blob = pgmagick.Blob()
     image.write(blob)
     self.raw = blob.data
     self.profile.mark_time('pgmagick')
     self.profile.mark('pgmagick_size', len(self.raw))
Exemplo n.º 11
0
def remove_background(filename):
    """ Remove the background of the image in 'filename' """

    img = pg.Image(filename)
    transmask = trans_mask_sobel(img)
    img = alphacomposite(transmask, img)
    img.trim()
    img.write('out.png')

    Question here: Does Java have pgmagick library or it's equivalent?
        
    To be continued...
    
    Updated code with histogram analysis:
        import pgmagick as pg
Exemplo n.º 12
0
    def _resize_using_pg(self, image, width, height, mode):
        """ Resize using image mode. """

        blob = pg.Blob(image)
        blob_out = pg.Blob()
        img = pg.Image(blob)
        img.filterType(pg.FilterTypes.LanczosFilter)

        img = process_image_with_mode(img, width, height, mode)

        # Image should be repaged after a crop/resize
        img.page(pg.Geometry(0, 0, 0, 0))
        img.quality(90)  # minimise artifacts but keep size down

        img.write(blob_out, 'JPEG')
        return blob_out.data, img.size().width(), img.size().height()
Exemplo n.º 13
0
def trans_mask_sobel(img):
    image = pg.Image(img)
    # Find object
    image.negate()
    image.edge()
    image.blur(1)
    image.threshold(24)
    image.adaptiveThreshold(5, 5, 5)
    # Fill background
    image.fillColor('magenta')
    w, h = image.size().width(), image.size().height()
    image.floodFillColor('0x0', 'magenta')
    image.floodFillColor('0x0+%s+0' % (w - 1), 'magenta')
    image.floodFillColor('0x0+0+%s' % (h - 1), 'magenta')
    image.floodFillColor('0x0+%s+%s' % (w - 1, h - 1), 'magenta')
    image.transparent('magenta')
    return image
Exemplo n.º 14
0
def _resizecomp(img, width, height):
    """ Used to be called 'normal'
        This:
          First performs a box resize on the original image
          Secondly, composites the image on to a white square of the required wxh
        Mode key: 'resizecomp'
    """

    img.scale('%sx%s' % (width, height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (int(width) - img.size().width()) / 2
    hdiff = (int(height) - img.size().height()) / 2
    backdrop.composite(img, wdiff, hdiff, pg.CompositeOperator.AtopCompositeOp)
    img = backdrop

    return img
Exemplo n.º 15
0
    def _resize_using_pg(self, image, width, height, mode):
        """ Resize using image mode. """

        blob = pg.Blob(image)
        blob_out = pg.Blob()
        img = pg.Image(blob)
        img.filterType(pg.FilterTypes.LanczosFilter)

        img = process_image_with_mode(img, width, height, mode)

        # Image should be repaged after a crop/resize
        img.page(pg.Geometry(0, 0, 0, 0))
        if settings.IMAGE_QUALITY is not None:  # May be handled by custom mode
            img.quality(settings.IMAGE_QUALITY)

        img.write(blob_out, 'JPEG')
        return blob_out.data, img.size().width(), img.size().height()
Exemplo n.º 16
0
def trans_mask_sobel(img, color="magenta"):
    """ Generate a transparency mask for a given image """
    image = pg.Image(img)
    # Find object
    image.negate()
    image.edge()
    image.blur(1)
    image.threshold(24)
    image.adaptiveThreshold(5, 5, 5)
    # Fill background
    image.fillColor(color)
    w, h = image.size().width(), image.size().height()
    image.floodFillColor('0x0', color)
    image.floodFillColor('0x0+%s+0' % (w - 1), color)
    image.floodFillColor('0x0+0+%s' % (h - 1), color)
    image.floodFillColor('0x0+%s+%s' % (w - 1, h - 1), color)
    image.transparent(color)
    return image
Exemplo n.º 17
0
def fingerprint_image(filename):
  img = pgmagick.Image(fix_gm_filename(filename))
  img.sample('160x160!')
  img.modulate(100.0, -100.0, 100.0)  # saturation=-100.
  img.blur(3, 99)  # radius=3, sigma=99.
  img.normalize()
  img.equalize()
  img.sample('16x16')
  img.threshold(half_threshold)
  img.magick('mono')
  blob = pgmagick.Blob()
  img.write(blob)
  # The output of the following command is identical to blob.data, but it's
  # diferent from `convert' (ImageMagick) instead of `gm
  # convert' (GraphicsMagick): even the output of (-sample '160x160!') is
  # different.
  #
  #   gm convert "${filename}" -sample '160x160!' -modulate 100,-100,100 -blur 3x99 -normalize -equalize -sample '16x16' -threshold 50% mono:t.out
  return blob.data  # 32 bytes.
Exemplo n.º 18
0
def _crop(img, width, height):
    """ This:
          First performs a box resize on the original image, but so only the smallest
            dimension is in the box. So if width was smaller, the image would be resized
            to Wx?
          Secondly, The image is cropped to the desired size, trimming the edges that are
            outside of the box
        Mode key: 'crop'
    """

    if img.size().width() < img.size().height():
        img.scale('%sx999999' % (width))
    else:
        img.scale('999999x%s' % (height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (img.size().width() - int(width)) / 2
    hdiff = (img.size().height() - int(height)) / 2
    backdrop.composite(img, -wdiff, -hdiff, pg.CompositeOperator.CopyCompositeOp)
    img = backdrop

    return img
Exemplo n.º 19
0
def _trim_resize(img, width, height):
    """ This:
          First performs a trim on the image with no color fuzz
          Secondly, performs a box resize on the original image only if the image is larger
            than the target size
          Thirdly, composites the image on to a white square of the required wxh
        Mode key: 'trimresize'
    """

    img.trim()

    w, h = img.size().width(), img.size().height()
    if w > int(width) or h > int(height):
        img.scale('%sx%s' % (width, height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (int(width) - img.size().width()) / 2
    hdiff = (int(height) - img.size().height()) / 2
    backdrop.composite(img, wdiff, hdiff, pg.CompositeOperator.AtopCompositeOp)
    img = backdrop

    return img
Exemplo n.º 20
0
def remove_background(filenameIn, filenameOut):
    img = pg.Image(filenameIn)
    transmask = trans_mask_sobel(img)
    img = alpha_composite(transmask, img)
    img.trim()
    img.write(filenameOut)
Exemplo n.º 21
0
 def __init__(self, filename):
     BaseImage.__init__(self, filename)
     self.image = pgmagick.Image(filename)
Exemplo n.º 22
0
#!/usr/bin/env python
import pgmagick

im = pgmagick.Image('existing.tif')

pdf = pgmagick.ImageList()
pdf.append(im)
pdf.append(im)
pdf.writeImages('new.pdf')

blob = pgmagick.Blob()
pdf.writeImages(blob)
print blob.length()
Exemplo n.º 23
0
# Initalize header for results
results = [["image1", "image2", "similar", "elapsed"]]

with open(cs) as file:
    reader = csv.reader(file)
    data = []
    # Reads each line into a list
    # [ [a,b], [c,d], ..]
    for r in reader:
        data.append(r)
    for d in data:
        # Checks if the file names are valid
        if '.' in d[0] and '.' in d[1]:
            try:
                # See if the images exist
                img1 = mag.Image(folder + d[0])
                img2 = mag.Image(folder + d[1])

                # Start the clock
                start_time = time.clock()

                # Get the similarity value
                diff = difference(img1, img2)

                # Remove any duplicates
                if diff == 0:
                    os.remove(folder + d[1])

                # End the clock
                end_time = round(time.clock() - start_time, 3)
                results.append([d[0], d[1], diff, end_time])
Exemplo n.º 24
0
def scale_face(uuid):
    skin = PythonMagick.Image(FILE_SKIN.format(uuid))
    skin.crop('8x8+8+8')
    skin.scale('128x128')
    skin.write(FILE_FACE.format(uuid))
Exemplo n.º 25
0
def sendGroupMessage(sessionKey, target, picurl, text='图来了', headers=None):
    time.sleep(0.25)
    log(picurl)
    try:
        if picurl is not None:
            if not os.path.exists(temp_path):
                os.makedirs(temp_path)
            timestr = str(time.time())
            picpath = os.path.join(
                temp_path, 'temp' + timestr + os.path.splitext(picurl)[1])
            ppicpath = os.path.join(temp_path, 'tmp' + timestr + '.png')
            log(picpath)
            # urlretrieve(picurl,filename=picpath)
            if headers is None:
                r = requests.get(picurl)
            else:
                r = requests.get(picurl, headers=headers)
            if r.status_code != 200:
                log(r.status_code)
                log('Failed to download', r.url)
                return
            with open(picpath, 'wb') as outfile:
                outfile.write(r.content)
                # outfile.write(b'Processed by NaiveTomcat')
            # command = 'cat '+picpath+' '+'/home/tomdang/setubot/mirai/core/data/net.mamoe.mirai-api-http/images/xyx.gif'+' > '+ppicpath
            # os.system(command)
            im = pgmagick.Image(picpath)
            # im.quality(100)
            im.write(ppicpath)
            log(ppicpath)
            url = mirai_url + '/sendGroupMessage'
            payload = {
                'sessionKey':
                sessionKey,
                'target':
                target,
                'messageChain': [{
                    'type': 'Plain',
                    'text': text
                }, {
                    'type':
                    'Image',
                    'path':
                    'temp' + timestr + os.path.splitext(picurl)[1]
                }, {
                    'type': 'Plain',
                    'text': ('URL: ' + picurl)
                }]
            }
        else:
            picpath = None
            url = mirai_url + '/sendGroupMessage'
            payload = {
                'sessionKey':
                sessionKey,
                'target':
                target,
                'messageChain': [{
                    'type': 'Plain',
                    'text': 'Result:\n'
                }, {
                    'type': 'Plain',
                    'text': text
                }]
            }
        # log(payload)
        # log(json.dumps(payload))
        headers = {'Content-Type': 'application/json'}
        r = requests.post(url, headers=headers, data=json.dumps(payload))
        # log(r.json())
        if r.status_code == 200 and r.json()['code'] == 0:
            log('Sent success')
        else:
            log('Failed to send')
            log(r.json())
        if picpath is not None:
            os.remove(picpath)
    finally:
        pass
Exemplo n.º 26
0
def pgmagick_scale(filename, width, height):
    im = pgmagick.Image(filename)
    im.scale('%dx%d' % (width, height))
    im.quality(95)
    im.write('outpg.jpg')
Exemplo n.º 27
0
def pgmagick_scale_from_blob(filename, width, height):
    im = pgmagick.Image(pgmagick.Blob(open(filename).read()),
                        pgmagick.Geometry(width, height))
    im.scale('%dx%d' % (width, height))
    im.quality(95)
    im.write('outpg_fromblob.jpg')
Exemplo n.º 28
0
-n: Don't find duplicates. Useful if combined with `-v fp'.
-v fp: Print base64 fingerprint of each input image.
"""

import base64
import itertools
import os
import re
import sys

# (pip install pgmagick) or (sudo apt-get install python-pgmagick)
import pgmagick


half_threshold = (1 << (pgmagick.Image().depth() - 1)) - 1  # 127.

diff_bit_threshold = 25


def fix_gm_filename(filename):
  """Prevent GraphicsMagick from treating files like logo: specially."""
  if not os.path.isabs(filename) and (
     filename.startswith('-') or filename.startswith('+') or
     ':' in filename):
    return os.path.join('.', filename)
  else:
    return filename


def fingerprint_image(filename):
    del img_list

    LOG.info(str(len(img_dict)) + " images found.")

    source_dimension_x = 0
    source_dimension_y = 0
    resized_width = 0
    resized_height = 0
    for image in img_dict.keys():
        #img = Image(filename=img_dict[image]['fullpath'])
        #img_dict[image]['exif:DateTimeDigitized'] = img.metadata['exif:DateTimeDigitized']
        #x = img.width
        #y = img.height

        # Use GraphicsMagick here since it is much faster. Uncomment the above lines and comment the next ones to use ImageMagick instead.
        img = pgmagick.Image(img_dict[image]['fullpath_original'])
        img_dict[image]['exif:DateTimeDigitized'] = img.attribute("exif:DateTimeDigitized")
        x = img.columns()
        y = img.rows()

        if source_dimension_x == 0 and source_dimension_y == 0:
            source_dimension_x = x
            source_dimension_y = y

            LOG.debug("Resolution of images is {}x{}".format(source_dimension_x, source_dimension_y))
            wide_side = source_dimension_x if source_dimension_x > source_dimension_y else source_dimension_y
            max_shake_px = int(math.ceil((options.max_shake /100.0) * wide_side))
            LOG.debug(u'Max shake is \u00B1{} pixels on the original picture size'.format(max_shake_px))

            if options.output_res != "original_size":
                if RESOLUTIONS[options.output_res][0] > source_dimension_x and RESOLUTIONS[options.output_res][1] > source_dimension_y:
    def render(self, out_path, size=10000, scale=5, bg_color='#0b131a'):
        """
        Render a PNG.
        """

        image = pgm.Image(
            pgm.Geometry(size, size),
            pgm.Color(bg_color),
        )

        # TODO: font

        nodes = self.graph.nodes_iter(data=True)
        count = len(self.graph)

        for tid, n in progress.bar(nodes, expected_size=count):

            # Get X/Y, radius.
            x = (n['x'] * scale) + (size / 2)
            y = -(n['y'] * scale) + (size / 2)
            r = (n['size'] * scale) / 2

            # Index the coordinates.
            self.graph.node[tid]['pixel_x'] = x
            self.graph.node[tid]['pixel_y'] = y
            self.graph.node[tid]['pixel_r'] = r

            # ** Node **

            # Hex-ify color.
            color = '#%02x%02x%02x' % (n['r'], n['g'], n['b'])

            # Draw the node.
            dl = pgm.DrawableList()
            dl.append(pgm.DrawableFillColor(color))
            dl.append(pgm.DrawableStrokeColor('black'))
            dl.append(pgm.DrawableStrokeWidth(r / 15))
            dl.append(pgm.DrawableStrokeOpacity(0.9))
            dl.append(pgm.DrawableCircle(x, y, x + r, y + r))
            image.draw(dl)

            # ** Label **

            label = ', '.join([
                n['label'],
                n['author'],
            ])

            # Measure the width of the label.
            image.fontPointsize(n['size'])
            tm = pgm.TypeMetric()
            image.fontTypeMetrics(label, tm)
            tw = tm.textWidth()

            # Draw the label.
            dl = pgm.DrawableList()
            dl.append(pgm.DrawablePointSize(n['size']))
            dl.append(pgm.DrawableFillColor('white'))
            dl.append(pgm.DrawableText(x - (tw / 2), y, label))
            image.draw(dl)

        image.write(os.path.abspath(out_path))