當前位置: 首頁>>代碼示例>>Python>>正文


Python ImageStat.Stat方法代碼示例

本文整理匯總了Python中PIL.ImageStat.Stat方法的典型用法代碼示例。如果您正苦於以下問題:Python ImageStat.Stat方法的具體用法?Python ImageStat.Stat怎麽用?Python ImageStat.Stat使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在PIL.ImageStat的用法示例。


在下文中一共展示了ImageStat.Stat方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: compare_images

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def compare_images(img1, img2):
    """Calculate the difference between two images of the same size
    by comparing channel values at the pixel level.
    `delete_diff_file`: removes the diff image after ratio found
    `diff_img_file`: filename to store diff image

    Adapted from Nicolas Hahn:
    https://github.com/nicolashahn/diffimg/blob/master/diffimg/__init__.py
    """

    # Don't compare if images are of different modes or different sizes.
    if (img1.mode != img2.mode) \
            or (img1.size != img2.size) \
            or (img1.getbands() != img2.getbands()):
        return None

    # Generate diff image in memory.
    diff_img = ImageChops.difference(img1, img2)
    # Calculate difference as a ratio.
    stat = ImageStat.Stat(diff_img)
    diff_ratio = sum(stat.mean) / (len(stat.mean) * 255)

    return diff_ratio * 100 
開發者ID:victordomingos,項目名稱:optimize-images,代碼行數:25,代碼來源:img_dynamic_quality.py

示例2: print_image

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def print_image(im, x_step=12, y_step=24, calc_average=False):
    W,H = im.size
    result = ""
    for i in range(0,H,y_step):
        for j in range(0,W,x_step):
            if calc_average:
                roi = im.crop((j,i,min(W-1,j+x_step),min(H-1,i+y_step)))
                col = ImageStat.Stat(roi).mean
            else:
                col = im.getpixel((min(W-1,j+x_step//2),min(H-1,i+y_step//2)))
            conf = color_mapper(*(col[:3]))
            result += color_text(*conf)
        result += "\n"
    return result

# convert a PIL image to ASCII art given output width in characters 
開發者ID:LingDong-,項目名稱:wechit,代碼行數:18,代碼來源:wechit.py

示例3: test_sanity

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def test_sanity(self):

        im = hopper()

        st = ImageStat.Stat(im)
        st = ImageStat.Stat(im.histogram())
        st = ImageStat.Stat(im, Image.new("1", im.size, 1))

        # Check these run. Exceptions will cause failures.
        st.extrema
        st.sum
        st.mean
        st.median
        st.rms
        st.sum2
        st.var
        st.stddev

        self.assertRaises(AttributeError, lambda: st.spam)

        self.assertRaises(TypeError, ImageStat.Stat, 1) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:23,代碼來源:test_imagestat.py

示例4: optimize

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def optimize(self, buffer, input_file, output_file):
        input_image = Image.open(input_file)
        stats = ImageStat.Stat(input_image).extrema
        has_alpha = False
        if len(stats) > 3 and (stats[3][0] < 255):
            has_alpha = True

        if has_alpha == False:
            intermediary = output_file + '-intermediate'
            input_image.save(intermediary, 'JPEG')
            input_file = intermediary

        command = '%s %s %s > /dev/null 2>&1' % (
            self.imgmin_path,
            input_file,
            output_file,
        )
        with open(os.devnull) as null:
            logger.debug("[AUTO IMGMIN] running: " + command)
            subprocess.call(command, shell=True, stdin=null) 
開發者ID:thumbor,項目名稱:thumbor-plugins,代碼行數:22,代碼來源:auto.py

示例5: _detect_color_image

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def _detect_color_image(file, thumb_size=150, MSE_cutoff=22, adjust_color_bias=True):
    # http://stackoverflow.com/questions/20068945/detect-if-image-is-color-grayscale-or-black-and-white-with-python-pil
    pilimg = Image.open(file)
    bands = pilimg.getbands()
    if bands == ("R", "G", "B") or bands == ("R", "G", "B", "A"):
        thumb = pilimg.resize((thumb_size, thumb_size))
        sse, bias = 0, [0, 0, 0]
        if adjust_color_bias:
            bias = ImageStat.Stat(thumb).mean[:3]
            bias = [b - sum(bias) / 3 for b in bias]
        for pixel in thumb.getdata():
            mu = sum(pixel) / 3
            sse += sum(
                (pixel[i] - mu - bias[i]) * (pixel[i] - mu - bias[i]) for i in [0, 1, 2]
            )
        mse = float(sse) / (thumb_size * thumb_size)
        return "grayscale" if mse <= MSE_cutoff else "color"
    elif len(bands) == 1:
        return "blackandwhite" 
開發者ID:pkkid,項目名稱:python-plexapi,代碼行數:21,代碼來源:test_server.py

示例6: create_before_and_after

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def create_before_and_after(
        recipient_faces: List[face_detect.Face],
        recipient_image: Image,
        donor_face: face_detect.Face = GABEN_FACE,
        donor_image: Image = GABEN_IMAGE) -> Image:
    logging.info('Locally processing image.')

    after_image = recipient_image

    assert len(recipient_faces) > 0
    for recipient_face in recipient_faces:
        after_image = _paste_donor_on_recipient(recipient_face, after_image, donor_face, donor_image)

    width, height = recipient_image.size
    final = Image.new("RGB", (width * 2, height))
    final.paste(recipient_image, (0, 0))
    final.paste(after_image, (width, 0))

    # if original image was grayscale, convert final
    colors = ImageStat.Stat(recipient_image).var
    if len(colors) == 3 and abs(max(colors) - min(colors)) < COLOR_CUTOFF:
        final = final.convert('L')

    return final 
開發者ID:revan,項目名稱:gabenizer,代碼行數:26,代碼來源:image_operations.py

示例7: getMean

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def getMean(self):
        if not self.mean:
            self.mean = ImageStat.Stat(self.im.convert('L')).mean[0]

        return self.mean 
開發者ID:kurtlab,項目名稱:pythonprojects,代碼行數:7,代碼來源:imagesmake.py

示例8: _average

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def _average(self):
        assert self.ret.__contains__('template_img_path'), 'no template path'
        assert self.ret.__contains__('detection_img_path'),'no detection path'
        template = Image.open(self.ret['template_img_path'])
        detection= Image.open(self.ret['detection_img_path'])
        
        mean_template = tuple(map(round, ImageStat.Stat(template).mean))
        mean_detection= tuple(map(round, ImageStat.Stat(detection).mean))
        self.ret['mean_template'] = mean_template
        self.ret['mean_detection']= mean_detection 
開發者ID:songdejia,項目名稱:Siamese-RPN-pytorch,代碼行數:12,代碼來源:data_loader.py

示例9: test_hopper

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def test_hopper(self):

        im = hopper()

        st = ImageStat.Stat(im)

        # verify a few values
        self.assertEqual(st.extrema[0], (0, 255))
        self.assertEqual(st.median[0], 72)
        self.assertEqual(st.sum[0], 1470218)
        self.assertEqual(st.sum[1], 1311896)
        self.assertEqual(st.sum[2], 1563008) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:14,代碼來源:test_imagestat.py

示例10: test_constant

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def test_constant(self):

        im = Image.new("L", (128, 128), 128)

        st = ImageStat.Stat(im)

        self.assertEqual(st.extrema[0], (128, 128))
        self.assertEqual(st.sum[0], 128**3)
        self.assertEqual(st.sum2[0], 128**4)
        self.assertEqual(st.mean[0], 128)
        self.assertEqual(st.median[0], 128)
        self.assertEqual(st.rms[0], 128)
        self.assertEqual(st.var[0], 0)
        self.assertEqual(st.stddev[0], 0) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:16,代碼來源:test_imagestat.py

示例11: pad

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def pad(image, npad, padding='avg'):
    if npad == 0:
        return image

    if padding == 'avg':
        avg_chan = ImageStat.Stat(image).mean
        # PIL doesn't support float RGB image
        avg_chan = tuple(int(round(c)) for c in avg_chan)
        image = ImageOps.expand(image, border=npad, fill=avg_chan)
    else:
        image = ImageOps.expand(image, border=npad, fill=padding)

    return image 
開發者ID:huanglianghua,項目名稱:open-vot,代碼行數:15,代碼來源:warp.py

示例12: pad_pil

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def pad_pil(image, npad, padding='avg'):
    if npad == 0:
        return image

    if padding == 'avg':
        avg_chan = ImageStat.Stat(image).mean
        # PIL doesn't support float RGB image
        avg_chan = tuple(int(round(c)) for c in avg_chan)
        image = ImageOps.expand(image, border=npad, fill=avg_chan)
    else:
        image = ImageOps.expand(image, border=npad, fill=padding)

    return image 
開發者ID:huanglianghua,項目名稱:open-vot,代碼行數:15,代碼來源:warp.py

示例13: crop_image

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def crop_image(image, box=None):
    """"Crop an image to a rectangle, filling with background.

    Given a PIL.Image ``image`` and a list ``box`` of the bounding
    rectangle relative to the image, crop at the box coordinates,
    filling everything outside ``image`` with the background.
    (This covers the case where ``box`` indexes are negative or
    larger than ``image`` width/height. PIL.Image.crop would fill
    with black.) Since ``image`` is not necessarily binarized yet,
    determine the background from the median color (instead of
    white).

    Return a new PIL.Image.
    """
    if not box:
        box = (0, 0, image.width, image.height)
    elif box[0] < 0 or box[1] < 0 or box[2] > image.width or box[3] > image.height:
        # (It should be invalid in PAGE-XML to extend beyond parents.)
        LOG.warning('crop coordinates (%s) exceed image (%dx%d)',
                    str(box), image.width, image.height)
    LOG.debug('cropping image to %s', str(box))
    xywh = xywh_from_bbox(*box)
    background = tuple(ImageStat.Stat(image).median)
    new_image = Image.new(image.mode, (xywh['w'], xywh['h']),
                          background) # or 'white'
    new_image.paste(image, (-xywh['x'], -xywh['y']))
    return new_image 
開發者ID:OCR-D,項目名稱:core,代碼行數:29,代碼來源:__init__.py

示例14: image_from_polygon

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def image_from_polygon(image, polygon, fill='background', transparency=False):
    """"Mask an image with a polygon.

    Given a PIL.Image ``image`` and a numpy array ``polygon``
    of relative coordinates into the image, fill everything
    outside the polygon hull to a color according to ``fill``:

    - if ``background`` (the default),
      then use the median color of the image;
    - otherwise use the given color, e.g. ``'white'`` or (255,255,255).

    Moreover, if ``transparency`` is true, then add an alpha channel
    from the polygon mask (i.e. everything outside the polygon will
    be transparent, for those consumers that can interpret alpha channels).
    Images which already have an alpha channel will have it shrunk
    from the polygon mask (i.e. everything outside the polygon will
    be transparent, in addition to existing transparent pixels).
    
    Return a new PIL.Image.
    """
    mask = polygon_mask(image, polygon)
    if fill == 'background':
        background = tuple(ImageStat.Stat(image).median)
    else:
        background = fill
    new_image = Image.new(image.mode, image.size, background)
    new_image.paste(image, mask=mask)
    # ensure no information is lost by a adding transparency channel
    # initialized to fully transparent outside the polygon mask
    # (so consumers do not have to rely on background estimation,
    #  which can fail on foreground-dominated segments, or white,
    #  which can be inconsistent on unbinarized images):
    if image.mode in ['RGBA', 'LA']:
        # ensure transparency maximizes (i.e. parent mask AND mask):
        mask = ImageChops.darker(mask, image.getchannel('A')) # min opaque
        new_image.putalpha(mask)
    elif transparency and image.mode in ['RGB', 'L']:
        # introduce transparency:
        new_image.putalpha(mask)
    return new_image 
開發者ID:OCR-D,項目名稱:core,代碼行數:42,代碼來源:__init__.py

示例15: is_color_image

# 需要導入模塊: from PIL import ImageStat [as 別名]
# 或者: from PIL.ImageStat import Stat [as 別名]
def is_color_image(file, thumb_size=50, MSE_cutoff=140, adjust_color_bias=True):
    try:
        pil_img = Image.open(file)
    except:
        print 'Couldn\'t open file %s'%file
        return False

    np_img = np.array(pil_img)
    if len(np_img.shape) > 2 and np_img.shape[2] > 1:
        if np.sum(np_img[:,:,1] - np_img[:,:,2]) == 0:
            print 'Grayscale'
            return False
    else:
        return False

    bands = pil_img.getbands()
    if bands == ('R','G','B') or bands== ('R','G','B','A'):
        thumb = pil_img.resize((thumb_size,thumb_size))
        SSE, bias = 0, [0,0,0]
        if adjust_color_bias:
            bias = ImageStat.Stat(thumb).mean[:3]
            bias = [b - sum(bias)/3 for b in bias ]
        for pixel in thumb.getdata():
            mu = sum(pixel)/3
            SSE += sum((pixel[i] - mu - bias[i])*(pixel[i] - mu - bias[i]) for i in [0,1,2])
        MSE = float(SSE)/(thumb_size*thumb_size)
        if MSE <= MSE_cutoff:
            print "grayscale\t",
            print "( MSE=",MSE,")"
            return False
        else:
            print "Color\t\t\t",
            print "( MSE=",MSE,")"

            return True
    elif len(bands)==1:
        print "Black and white", bands
        return False
    else:
        print "Don't know...", bands
        return False 
開發者ID:dannyvai,項目名稱:reddit_crawlers,代碼行數:43,代碼來源:image_util.py


注:本文中的PIL.ImageStat.Stat方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。