Monday 15 March 2010

python - Is it possible to do additive blending with matplotlib? -



python - Is it possible to do additive blending with matplotlib? -

when dealing overlapping high density scatter or line plots of different colors can convenient implement additive blending schemes, rgb colors of each marker add together produce final color in canvas. mutual operation in 2d , 3d render engines.

however, in matplotlib i've found back upwards alpha/opacity blending. there roundabout way of doing or stuck rendering bitmap , blending them in paint program?

edit: here's illustration code , manual solution.

this produce 2 partially overlapping random distributions:

x1 = randn(1000) y1 = randn(1000) x2 = randn(1000) * 5 y2 = randn(1000) scatter(x1,y1,c='b',edgecolors='none') scatter(x2,y2,c='r',edgecolors='none')

this produce in matplotlib following:

as can see, there overlapping bluish points occluded reddish points , see them. using alpha/opacity blending in matplotlib, can do:

scatter(x1,y1,c='b',edgecolors='none',alpha=0.5) scatter(x2,y2,c='r',edgecolors='none',alpha=0.5)

which produce following:

but want following:

i can manually rendering each plot independently bitmap:

xlim = plt.xlim() ylim = plt.ylim() scatter(x1,y1,c='b',edgecolors='none') plt.xlim(xlim) plt.ylim(ylim) scatter(x2,y2,c='r',edgecolors='none') plt.xlim(xlim) plt.ylim(ylim) plt.savefig(r'scatter_blue.png',transparent=true) plt.savefig(r'scatter_red.png',transparent=true)

which gives me next images:

what can load them independent layers in paint.net/photoshop/gimp , additive blend them.

now ideal able programmatically in matplotlib, since i'll processing hundreds of these!

if need image result, can canvas buffer numpy array, , blending, here example:

from matplotlib import pyplot plt import numpy np fig, ax = plt.subplots() ax.scatter(x1,y1,c='b',edgecolors='none') ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.patch.set_facecolor("none") ax.patch.set_edgecolor("none") fig.canvas.draw() w, h = fig.canvas.get_width_height() img = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy() ax.clear() ax.scatter(x2,y2,c='r',edgecolors='none') ax.set_xlim(-4, 4) ax.set_ylim(-4, 4) ax.patch.set_facecolor("none") ax.patch.set_edgecolor("none") fig.canvas.draw() img2 = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy() img[img[:, :, -1] == 0] = 0 img2[img2[:, :, -1] == 0] = 0 fig.clf() plt.imshow(np.maximum(img, img2)) plt.subplots_adjust(0, 0, 1, 1) plt.axis("off") plt.show()

the result:

python matplotlib blending color-blending

No comments:

Post a Comment