Skip to content

Instantly share code, notes, and snippets.

@tatome
Last active March 12, 2021 07:24
Show Gist options
  • Save tatome/e029e61a50d39090eb56 to your computer and use it in GitHub Desktop.
Save tatome/e029e61a50d39090eb56 to your computer and use it in GitHub Desktop.
Plot any RGB image as as pcolormesh in matplotlib's pcolormesh
import numpy as np
def plot_as_colormesh(image, axes, **pcolormeshkwargs):
raveled_pixel_shape = (image.shape[0]*image.shape[1], image.shape[2])
color_tuple = image.transpose((1,0,2)).reshape(raveled_pixel_shape)
if color_tuple.dtype == np.uint8:
color_tuple = color_tuple / 255.
index = np.tile(np.arange(image.shape[0]), (image.shape[1],1))
quad = axes.pcolormesh(index, color=color_tuple, linewidth=0, **pcolormeshkwargs)
quad.set_array(None)
if __name__ == '__main__':
import urllib2
import cv2
from matplotlib import pyplot as plt
sample_image = urllib2.urlopen('http://imgs.xkcd.com/comics/grownups.png').read()
sample_image = np.fromstring(sample_image, np.uint8)
sample_image = cv2.imdecode(sample_image, cv2.CV_LOAD_IMAGE_COLOR)
sample_image = cv2.cvtColor(sample_image, cv2.COLOR_BGR2RGB)
sample_image = cv2.transpose(sample_image)[:,::-1]
axes = plt.axes()
plot_as_colormesh(sample_image, axes)
plt.show()
@tatome
Copy link
Author

tatome commented Jul 15, 2015

This is probably not a good way to plot your high-res holiday pictures, but if you have some sort of bitmap-like figure in which you want to control colors precisely, this lets you generate a scalable plot (and save it e.g. as svg/pdf).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment