4

I'm trying to copy an image by hand, but I when I do the result is a negative of the original image. I can't seem to find out why, so please help.

This is the code:

def copy(image):
    padded_image = np.ndarray(shape=image.shape)
    for i in xrange(0, image.shape[0]):
        for j in xrange(0, image.shape[1]):
            padded_image[i][j] = image[i][j]

    return padded_image

enter image description here

This is how I read the image:

jelly_beans = io.imread("4.1.07-jelly-beans.tiff")

And this is how I display the images:

    def show_images(images, titles = None):

        """Display a list of images"""
        n_ims = len(images)
        if titles is None: titles = ['(%d)' % i for i in range(1,n_ims + 1)]
        fig = plt.figure()
        n = 1
        for image,title in zip(images,titles):
            a = fig.add_subplot(1,n_ims,n) # Make subplot
            if image.ndim == 2: # Is image grayscale?
                plt.gray() 
            plt.imshow(image)
            a.set_title(title)
            n += 1
        fig.set_size_inches(np.array(fig.get_size_inches()) * n_ims)
        plt.show()

1 Answers1

4

The problem is that when you created padded_image using ndarray, you didn't specify a dtype so it defaulted to floating point. Then you use imshow to display a floating point array with values that are not normalized in the range [0, 1], so imshow does some sort of normalization of its own, resulting in "opposite" colors. (Not all floating point images will be reversed like that.)

You can fix that by using

padded_image = np.ndarray(shape=image.shape, dtype=image.dtype)

That should fix the immediate problem. A better fix is to simply not write your own copy function. The numpy ndarray has a copy method, so you can do, for example,

image2 = image1.copy()
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214