anonygrits
anonygrits

Reputation: 1499

python matplotlib image - invert white & black as default

I'm starting to play with openCV & am working through the Programming Computer Vision with Python book. It seems like I have a default that's set as the inverse (or reverse?) of what the book is using because where the image is black on my computer, the image is white in the book.

Is there any way to set the default to flip the white & black without doing a calculation each time?

Here's some sample code from the book. In the book, the background is white, but on my computer, it is black:

from PIL import Image
from numpy import *
from scipy.ndimage import filters

im = array(Image.open('empire.jpg').convert('L'))

sigma = 5
imx = zeros(im.shape)
filters.gaussian_filter(im,(sigma,sigma),(0,1),imx)  
imy = zeros(im.shape)
filters.gaussian_filter(im,(sigma,sigma),(1,0),imy)  
magnitude = sqrt(imx**2+imy**2)  

figure()  
subplot(1,4,1)
imshow(im)
subplot(1,4,2)
imshow(imx)
subplot(1,4,3)
imshow(imy)
subplot(1,4,4)
imshow(magnitude)

I'm on a mac book pro & using python 2.7. This has probably been answered somewhere, but I couldn't find an answer - probably not using the right tags/keywords... thx in advance.

Upvotes: 3

Views: 7184

Answers (2)

Élio Pereira
Élio Pereira

Reputation: 221

As suggested by @tacaswell in the comments of OP's question, you may use the color map gray_r in matplotlib pyplot's imshow method for having a reverse gray plot. Alternatively, you may use color maps binary and gist_yarg (as shown in matplotlib's documentation). Just a curiosity: notice the pun in the term "gist_yarg": "yarg" is "gray" written in the reverse order.

As an illustrative example, to plot OP's image im with reverse gray colormap, one could do:

from PIL import Image
import matplotlib.pyplot as plt

im = array(Image.open('empire.jpg').convert('L'))

plt.imshow(X=im, cmap="gray_r")

Upvotes: 0

Lucas Lopes
Lucas Lopes

Reputation: 936

It's not default, but you can invert the colors by subtract the array from 1:

plt.imshow(1 - array)

Upvotes: 1

Related Questions