Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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)
if __name__ == '__main__':
import urllib2
import cv2
from matplotlib import pyplot as plt
sample_image = urllib2.urlopen('').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)

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.