Python PIL.ImageChops.difference() Examples

The following are 30 code examples of PIL.ImageChops.difference(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageChops , or try the search function .
Example #1
Source File: img_dynamic_quality.py    From optimize-images with MIT License 13 votes vote down vote up
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 
Example #2
Source File: Image_Compare.py    From qxf2-page-object-model with MIT License 7 votes vote down vote up
def analyze_difference_smartly(img):
    "Make an evaluation of a difference image"
    result_flag = False
    if not os.path.exists(img):
        print('Could not locate the image to analyze the difference smartly: %s'%img)
    else:
        my_image = Image.open(img)
        #Not an ideal line, but we dont have any enormous images
        pixels = list(my_image.getdata())
        pixels = [1 for x in pixels if x!=0]
        num_different_pixels = sum(pixels)
        print('Number of different pixels in the result image: %d'%num_different_pixels)
        #Rule 1: If the number of different pixels is <10, then pass the image
        #This is relatively safe since all changes to objects will be more than 10 different pixels
        if num_different_pixels < 10:
            result_flag = True

    return result_flag 
Example #3
Source File: test_image_process.py    From image_process with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_transforms(self):
        settings = get_settings(IMAGE_PROCESS=self.transforms)

        def test_transform(d, i, tmpdir):
            path, name = os.path.split(i)
            destination = os.path.join(tmpdir, d, name)
            image = (i, destination, settings["IMAGE_PROCESS"][d])

            process_image(image, settings)

            transformed = Image.open(destination)

            expected_path = os.path.join(path, "results", d, name)
            expected = Image.open(expected_path)

            img_diff = ImageChops.difference(transformed, expected).getbbox()

            self.assertEqual(img_diff, None)

        with temporary_folder() as tmpdir:
            [
                test_transform(d, i, tmpdir)
                for d in self.transforms
                for i in TEST_IMAGES
            ] 
Example #4
Source File: imgcompare.py    From Dindo-Bot with MIT License 6 votes vote down vote up
def pixel_diff(image_a, image_b):
    """
    Calculates a black/white image containing all differences between the two input images.

    :param image_a: input image A
    :param image_b: input image B
    :return: a black/white image containing the differences between A and B
    """

    if image_a.size != image_b.size:
        raise ImageCompareException(
            "different image sizes, can only compare same size images: A=" + str(image_a.size) + " B=" + str(
                image_b.size))

    if image_a.mode != image_b.mode:
        raise ImageCompareException(
            "different image mode, can only compare same mode images: A=" + str(image_a.mode) + " B=" + str(
                image_b.mode))

    diff = ImageChops.difference(image_a, image_b)
    diff = diff.convert('L')

    return diff 
Example #5
Source File: extractor.py    From imago-forensics with MIT License 6 votes vote down vote up
def ela(filename, output_path):
    print "****ELA is in BETA****"
    if magic.from_file(filename, mime=True) == "image/jpeg":
        quality_level = 85
        tmp_img = os.path.join(output_path,os.path.basename(filename)+".tmp.jpg")
        ela = os.path.join(output_path,os.path.basename(filename)+".ela.jpg")
        image = Image.open(filename)
        image.save(tmp_img, 'JPEG', quality=quality_level)
        tmp_img_file = Image.open(tmp_img)
        ela_image = ImageChops.difference(image, tmp_img_file)
        extrema = ela_image.getextrema()
        max_diff = max([ex[1] for ex in extrema])
        scale = 255.0/max_diff
        ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
        ela_image.save(ela)
        os.remove(tmp_img)
    else:
        print "ELA works only with JPEG"


#Modified version of a gist by: https://github.com/erans 
Example #6
Source File: visualization.py    From qiskit-terra with Apache License 2.0 6 votes vote down vote up
def assertImagesAreEqual(self, current, expected, diff_tolerance=0.001):
        """Checks if both images are similar enough to be considered equal.
        Similarity is controlled by the ```diff_tolerance``` argument."""
        from PIL import Image, ImageChops

        if isinstance(current, str):
            current = Image.open(current)
        if isinstance(expected, str):
            expected = Image.open(expected)

        diff = ImageChops.difference(expected, current)
        black_pixels = _get_black_pixels(diff)
        total_pixels = diff.size[0] * diff.size[1]
        similarity_ratio = black_pixels / total_pixels
        self.assertTrue(
            1 - similarity_ratio < diff_tolerance,
            'The images are different by {}%'.format((1 - similarity_ratio) * 100) +
            ' which is more than the allowed {}%'.format(diff_tolerance * 100)) 
Example #7
Source File: test_rest.py    From picasso with Eclipse Public License 1.0 6 votes vote down vote up
def verify_data(client, data, vis, prefix=''):
    res_path = './tests/resources/'
    assert data['input_file_name']
    assert data['predict_probs']
    if data['has_output']:
        assert data['output_file_names']
        i = 1
        for filename in data['output_file_names']:
            actual_image = client.get(url_for('api.download_outputs', filename=filename)).data
            actual_processed_input = Image.open(io.BytesIO(actual_image))
            expected_processed_input = Image.open(res_path + vis.__name__ + '/' + prefix + 'output/' + str(i) + '.png')
            assert ImageChops.difference(actual_processed_input, expected_processed_input).getbbox() is None
            i += 1
    if data['has_processed_input']:
        assert data['processed_input_file_name']
        filename = data['processed_input_file_name']
        actual_image = client.get(url_for('api.download_outputs', filename=filename)).data
        actual_processed_input = Image.open(io.BytesIO(actual_image))
        expected_processed_input = Image.open(res_path + vis.__name__ + '/' + prefix + 'pre/default.png')
        assert ImageChops.difference(actual_processed_input, expected_processed_input).getbbox() is None 
Example #8
Source File: oled.py    From i2cdriver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def image(self, im):
        for p in range(8):
            pr = self.im.crop((0,8*p,128,8*p+8)).transpose(Image.ROTATE_270)
            bb = im.crop((0,8*p,128,8*p+8)).transpose(Image.ROTATE_270)
            diff = ImageChops.difference(pr, bb)
            di = diff.getbbox()
            if di is not None:
                (x0, y0, x1, y1) = di
                self.command(COLUMNADDR)
                self.command(y0)
                self.command(y1 - 1)
                self.command(PAGEADDR)
                self.command(p)
                self.command(p + 1)
                self.i2.start(self.a, 0)
                self.i2.write([0x40])
                self.i2.write(bb.tobytes()[y0:y1])
                self.i2.stop()
        self.im = im
        self.command(DISPLAYON) 
Example #9
Source File: img_dynamic_quality.py    From optimize-images with MIT License 6 votes vote down vote up
def get_diff_at_quality(photo, quality):
    """Return a difference score for this JPEG image saved at the specified quality

    A SSIM score would be much better, but currently there is no pure Python
    implementation available.
    """
    diff_photo = BytesIO()
    # optimize is omitted here as it doesn't affect
    # quality but requires additional memory and cpu
    photo.save(diff_photo, format="JPEG", quality=quality, progressive=True)
    diff_photo.seek(0)
    diff_score = compare_images(photo, Image.open(diff_photo))

    # print("================> DIFF1 == DIFF2? ", diff_score==diff_score2)

    if diff_score < 0:
        return -1 + diff_score / 100
    else:
        return 1 - diff_score / 100 
Example #10
Source File: display.py    From epd-library-python with GNU General Public License v3.0 6 votes vote down vote up
def _compute_diff_box(cls, a, b, round_to=2):
        '''
        Find the four coordinates giving the bounding box of differences between a and b
        making sure they are divisible by round_to

        Parameters
        ----------

        a : PIL.Image
            The first image

        b : PIL.Image
            The second image

        round_to : int
            The multiple to align the bbox to
        '''
        box = ImageChops.difference(a, b).getbbox()
        if box is None:
            return None
        return cls._round_bbox(box, round_to) 
Example #11
Source File: Image_Compare.py    From makemework with MIT License 6 votes vote down vote up
def analyze_difference_smartly(img):
    "Make an evaluation of a difference image"
    result_flag = False
    if not os.path.exists(img):
        print('Could not locate the image to analyze the difference smartly: %s'%img)
    else:
        my_image = Image.open(img)   
        #Not an ideal line, but we dont have any enormous images
        pixels = list(my_image.getdata())
        pixels = [1 for x in pixels if x!=0]
        num_different_pixels = sum(pixels)
        print('Number of different pixels in the result image: %d'%num_different_pixels)
        #Rule 1: If the number of different pixels is <10, then pass the image
        #This is relatively safe since all changes to objects will be more than 10 different pixels
        if num_different_pixels < 10:
            result_flag = True

    return result_flag 
Example #12
Source File: test_drawing.py    From discopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_draw_bell_state():
    return circuit.H @ circuit.Id(1) >> circuit.CX


# def test_Diagram_to_gif():
#     file = 'EckmannHilton.gif'
#     path_ref = os.path.join(IMG_FOLDER, file)
#     path_test = os.path.join(IMG_FOLDER, '.' + file)
#
#     step0 = Box('s0', Ty(), Ty()) @ Box('s1', Ty(), Ty())
#     step1 = next(step0.normalize())
#     Diagram.to_gif(
#         step0, step1,
#         loop=True, margins=(0.1, 0.1), figsize=(3, 3),
#         path=path_test)
#
#     img_ref = Image.open(path_ref).convert('RGB')
#     img_test = Image.open(path_test).convert('RGB')
#     assert ImageChops.difference(img_ref, img_test).getbbox() is None
#     os.remove(path_test) 
Example #13
Source File: test_icon_font.py    From icon-font-to-png with MIT License 6 votes vote down vote up
def test_size(font_awesome, image, size):
    """Test size option"""
    original_file = os.path.join(BASE_DIR, 'files', image)

    font_awesome.export_icon(icon='rocket', size=size)
    exported_file = os.path.join('exported', 'rocket.png')

    img1 = Image.open(original_file)
    img2 = Image.open(exported_file)

    # Check dimensions
    assert img1.size == (size, size)
    assert img2.size == (size, size)

    # Check if the images are equal
    assert ImageChops.difference(img1, img2).getbbox() is None 
Example #14
Source File: display.py    From IT8951 with MIT License 6 votes vote down vote up
def _compute_diff_box(cls, a, b, round_to=2):
        '''
        Find the four coordinates giving the bounding box of differences between a and b
        making sure they are divisible by round_to

        Parameters
        ----------

        a : PIL.Image
            The first image

        b : PIL.Image
            The second image

        round_to : int
            The multiple to align the bbox to
        '''
        box = ImageChops.difference(a, b).getbbox()
        if box is None:
            return None
        return cls._round_bbox(box, round_to) 
Example #15
Source File: imgcompare.py    From Dindo-Bot with MIT License 5 votes vote down vote up
def image_diff_percent(image_a, image_b):
    """
    Calculate the difference between two images in percent.

    :param image_a: input image A
    :param image_b: input image B
    :return: the difference between the images A and B as percentage
    """

    # if paths instead of image instances where passed in
    # load the images
    if isinstance(image_a, str):
        image_a = Image.open(image_a)

    if isinstance(image_b, str):
        image_b = Image.open(image_b)

    # first determine difference of input images
    input_images_histogram_diff = image_diff(image_a, image_b)

    # to get the worst possible difference use a black and a white image
    # of the same size and diff them

    black_reference_image = Image.new('RGB', image_a.size, (0, 0, 0))
    white_reference_image = Image.new('RGB', image_a.size, (255, 255, 255))

    worst_bw_diff = image_diff(black_reference_image, white_reference_image)

    percentage_histogram_diff = (input_images_histogram_diff / float(worst_bw_diff)) * 100

    return percentage_histogram_diff 
Example #16
Source File: imgcompare.py    From Dindo-Bot with MIT License 5 votes vote down vote up
def image_diff(image_a, image_b):
    """
    Calculates the total difference "score" of two images. (see imagecompare.total_histogram_diff).

    :param image_a: input image A
    :param image_b: input image A
    :return: the total difference "score" between two images
    """
    histogram_diff = total_histogram_diff(pixel_diff(image_a, image_b))

    return histogram_diff 
Example #17
Source File: screenshot.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def equal(self, img1, img2, skip_area=None):
        """Compares two screenshots using Root-Mean-Square Difference (RMS).
        @param img1: screenshot to compare.
        @param img2: screenshot to compare.
        @return: equal status.
        """
        if not HAVE_PIL:
            return None

        # Trick to avoid getting a lot of screen shots only because the time in the windows
        # clock is changed.
        # We draw a black rectangle on the coordinates where the clock is locates, and then
        # run the comparison.
        # NOTE: the coordinates are changing with VM screen resolution.
        if skip_area:
            # Copying objects to draw in another object.
            img1 = img1.copy()
            img2 = img2.copy()
            # Draw a rectangle to cover windows clock.
            for img in (img1, img2):
                self._draw_rectangle(img, skip_area)

        # To get a measure of how similar two images are, we use
        # root-mean-square (RMS). If the images are exactly identical,
        # this value is zero.
        diff = ImageChops.difference(img1, img2)
        h = diff.histogram()
        sq = (value * ((idx % 256)**2) for idx, value in enumerate(h))
        sum_of_squares = sum(sq)
        rms = math.sqrt(sum_of_squares/float(img1.size[0] * img1.size[1]))

        # Might need to tweak the threshold.
        return rms < 8 
Example #18
Source File: LicGLHelpers.py    From lic with GNU General Public License v3.0 5 votes vote down vote up
def _getBounds(size, glDispID, filename, scale, rotation, partRotation):
    
    # Clear the drawing buffer with white
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    
    # Draw the piece in black
    glColor3f(0, 0, 0)
    adjustGLViewport(0, 0, size, size)
    rotateToView(rotation, scale)
    rotateView(*partRotation)

    glCallList(glDispID)

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

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

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

    # Find the bottom left corner inset, used for placing PLIItem quantity labels
    data = img.load()
    leftInset = _getLeftInset(data, size, box[1])
    bottomInset = _getBottomInset(data, size, box[0])
    return box + (leftInset - box[0], bottomInset - box[1]) 
Example #19
Source File: imgcompare.py    From Dindo-Bot with MIT License 5 votes vote down vote up
def total_histogram_diff(pixel_diff):
    """
    Sums up all histogram values of an image. When used with the black/white pixel-diff image
    this gives the difference "score" of an image.

    :param pixel_diff: the black/white image containing all differences (output of imagecompare.pixel_diff function)
    :return: the total "score" of histogram values (histogram values of found differences)
    """
    return sum(i * n for i, n in enumerate(pixel_diff.histogram())) 
Example #20
Source File: example_basic.py    From deeptam with GNU General Public License v3.0 5 votes vote down vote up
def simple_visualization(image_key, image_cur, image_cur_virtual, frame_id):
    """Visualizes some image results
    
    image_key, image_cur, image_cur_virtual: np.array
    
    frame_id: int
    """
    image_key = convert_array_to_colorimg(image_key.squeeze())
    image_cur = convert_array_to_colorimg(image_cur.squeeze())
    image_cur_virtual = convert_array_to_colorimg(image_cur_virtual.squeeze())  
    
    diff = ImageChops.difference(image_cur, image_cur_virtual) # difference should be small if the predicted pose is correct

    print('Close window to continue...')
    
    plt.subplot(2,2,1)
    plt.gca().set_title('Key frame image')
    fig = plt.imshow(image_key)
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.subplot(2,2,2)
    plt.gca().set_title('Current frame image {}'.format(frame_id))
    fig = plt.imshow(image_cur)
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.subplot(2,2,3)
    plt.gca().set_title('Virtual current frame image {}'.format(frame_id))
    fig = plt.imshow(image_cur_virtual)
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.subplot(2,2,4)
    plt.gca().set_title('Difference image')
    fig = plt.imshow(diff)
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)

    plt.show() 
Example #21
Source File: Capture_images_Chong_windows_BUM06_5.py    From 3D-Scene-GAN with GNU General Public License v3.0 5 votes vote down vote up
def equal(im1, im2):
  return ImageChops.difference(im1, im2).getbbox() is None

#width = 1288
#height = 725
#x_point = 269
#y_point = 123

# The new parameters are full screen mode in shwde7518 with Ctrl+above arrow 
Example #22
Source File: login.py    From AutoYtB with The Unlicense 5 votes vote down vote up
def find_different_point_offset(image1, image2):
    diff_image = ImageChops.difference(image1, image2)
    width, height = diff_image.size
    offset_array = []
    for h in range(height):
        for w in range(width):
            r, g, b = diff_image.getpixel((w, h))
            min_rgb = min(r, g, b)
            max_rgb = max(r, g, b)
            if max_rgb - min_rgb > 40 or max_rgb > 50:
                offset_array.append(w)
                break
    offset = min(offset_array)
    return offset 
Example #23
Source File: image_operations_test.py    From gabenizer with MIT License 5 votes vote down vote up
def _assertImagesEqual(self, new, expect):
        diff = ImageChops.difference(new, expect)
        self.assertFalse(diff.getbbox(), 'Images differ!') 
Example #24
Source File: example_advanced_sequence.py    From deeptam with GNU General Public License v3.0 5 votes vote down vote up
def update_visualization(axes, pr_poses, gt_poses, image_cur, image_cur_virtual):
    """ Updates the visualization for tracking
    
    axes: a list of plt.axes
    
    pr_poses, gt_poses: a list of Pose
    
    image_cur, image_cur_virtual: np.array
    
    """
    pr_poses_c2w = [convert_between_c2w_w2c(x) for x in pr_poses]
    gt_poses_c2w = [convert_between_c2w_w2c(x) for x in gt_poses]
    
    axes[0].plot(np.array([x.t[0] for x in pr_poses_c2w]),
            np.array([x.t[1] for x in pr_poses_c2w]),
            np.array([x.t[2] for x in pr_poses_c2w]),
            'r',
            label='Prediction')
    
    axes[0].plot(np.array([x.t[0] for x in gt_poses_c2w]),
            np.array([x.t[1] for x in gt_poses_c2w]),
            np.array([x.t[2] for x in gt_poses_c2w]),
            'g',
            label='Ground truth')

    if image_cur_virtual is not None:
        image_cur = convert_array_to_colorimg(image_cur.squeeze())
        image_cur_virtual = convert_array_to_colorimg(image_cur_virtual.squeeze()) 
        diff = ImageChops.difference(image_cur, image_cur_virtual)
        axes[1].cla()
        axes[1].set_title('Current image')
        axes[2].cla()
        axes[2].set_title('Virtual current image')
        axes[3].cla()
        axes[3].set_title('Diff image')
        axes[1].imshow(np.array(image_cur))       
        axes[2].imshow(np.array(image_cur_virtual))
        axes[3].imshow(np.array(diff))

    plt.pause(1e-9) 
Example #25
Source File: pildriver.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def do_subtract(self):
        """usage: subtract <image:pic1> <image:pic2> <int:offset> <float:scale>

        Pop the two top images, produce the scaled difference with offset.
        """
        from PIL import ImageChops
        image1 = self.do_pop()
        image2 = self.do_pop()
        scale = float(self.do_pop())
        offset = int(self.do_pop())
        self.push(ImageChops.subtract(image1, image2, scale, offset))

    # ImageEnhance classes 
Example #26
Source File: image_compare.py    From AXUI with Apache License 2.0 5 votes vote down vote up
def image_compare(image1, image2, diff_image_name="diff.bmp"):
    '''compare two images, return difference percentage
    #code from http://rosettacode.org/wiki/Percentage_difference_between_images#Python
    '''
    gen_diff_image = image_config.gen_diff_image
    diff_image_location = image_config.diff_image_location

    i1 = Image.open(image1)
    i2 = Image.open(image2)
    assert i1.mode == i2.mode, "Different kinds of images: %s VS %s" % (i1.mode, i2.mode)
    assert i1.size == i2.size, "Different sizes: %s, %s" % (i1.size, i2.size)
    
    #generate diff bitmap
    if gen_diff_image:
        diff = ImageChops.difference(i1, i2)
        diff_image_path = os.path.join(diff_image_location, diff_image_name)
        diff.save(diff_image_path)
        LOGGER.debug("Diff image save to: %s" % diff_image_path)
    
    #caculate the diff percentage
    pairs = zip(i1.getdata(), i2.getdata())
    if len(i1.getbands()) == 1:
        # for gray-scale jpegs
        dif = sum((p1==p2) and 1 or 0 for p1,p2 in pairs)
    else:
        dif = sum((c1==c2) and 1 or 0 for p1,p2 in pairs for c1,c2 in zip(p1,p2))
     
    ncomponents = i1.size[0] * i1.size[1] * 3
    dif_percentage = float(dif) / ncomponents
    LOGGER.debug("Difference (percentage): %f" % dif_percentage)
    return dif_percentage 
Example #27
Source File: test_storylayer_thumbnail.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def compare_images(img1, img2, rgb_difference=1):
    """compare two images.
       rgb_difference = how different pixels need to be to be considered different
                     1 -> any difference is detected
                     n -> larger means minor differences aren't detected (see code)
       different sizes ==> exception
       otherwise, return the % of pixels that aren't the same in the images.
       """
    # make sure they are RGB
    img1 = img1.convert("RGB")
    img2 = img2.convert("RGB")
    if img1.size[0] != img2.size[0] or img1.size[1] != img2.size[1]:
        raise Exception("compare_images - images aren't the same size")
    diffImage = ImageChops.difference(img1, img2)
    differentPixels = 0
    for w in range(0, diffImage.width):
        for h in range(0, diffImage.height):
            pixel = diffImage.getpixel((w, h))
            difference = pixel[0] + pixel[1] + \
                pixel[2]  # absolute pixel difference
            if difference > rgb_difference:
                differentPixels += 1
    return differentPixels / (img1.size[0] * img1.size[1])


# simple tests to verify that the image comparer (compare_images) is working correctly 
Example #28
Source File: test_storylayer_thumbnail.py    From mapstory with GNU General Public License v3.0 5 votes vote down vote up
def test_animated_GIF_creation(self):
        thumb_generator = CreateStoryLayerAnimatedThumbnailTask()
        fnames = [
            os.path.realpath(
                "mapstory/thumbnails/test_imgs/railroads-thumb-correct.png"),
            os.path.realpath(
                "mapstory/thumbnails/test_imgs/railroads-thumb-no_basemap.png"),
            os.path.realpath(
                "mapstory/thumbnails/test_imgs/railroads-thumb-no_wms.png")
        ]
        orig_images = [Image.open(fname) for fname in fnames]

        gif_data = thumb_generator.create_animated_GIF(fnames)
        image_file = StringIO(gif_data)
        gif_image = Image.open(image_file)

        self.assertTrue(gif_image.is_animated)
        self.assertEqual(gif_image.n_frames, 3)

        frames = [Image.new('RGBA', gif_image.size), Image.new('RGBA', gif_image.size),
                  Image.new('RGBA', gif_image.size)]
        gif_image.seek(0)
        frames[0].paste(gif_image)
        gif_image.seek(1)
        frames[1].paste(gif_image)
        gif_image.seek(2)
        frames[2].paste(gif_image)

        # due to pallet differences, we allow a little bit of difference
        self.assertTrue(compare_images(orig_images[0], frames[0], 14) < 0.05)
        self.assertTrue(compare_images(orig_images[1], frames[1], 14) < 0.05)
        self.assertTrue(compare_images(orig_images[2], frames[2], 14) < 0.05)

    # note - while this is running, there is likely a thumbnail generation task occuring in the background
    # (kicked off by the importer)
    #   So, the layer may or may not have a thumbnail attached to it (and might have one in the future). 
Example #29
Source File: test_roundtrip.py    From blender-md3 with MIT License 5 votes vote down vote up
def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"
    h = ImageChops.difference(im1, im2).histogram()
    return sqrt(
        sum(map(lambda h, i: h*(i**2), h, range(256)))
        /
        (im1.size[0] * im1.size[1]),
    ) 
Example #30
Source File: photos.py    From GooglePhotosStorage with GNU General Public License v2.0 5 votes vote down vote up
def get_image_char(image):                  #This function comes from here: https://github.com/Lukasa/entweet and is used to calculate the character in a given image
    diffs = {}
    for char, char_image in image_map.items():
        diff = ImageChops.difference(image, char_image)
        if diff.getbbox() is None:
            return char
        diffs[char] = diff
    min_rms = 10**6
    closest_char = ''
    for char, diff in diffs.items():
        rms = rmsdiff(diff)
        if rms < min_rms:
            min_rms = rms
            closest_char = char
    return closest_char