Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

python - matplotlib 3D scatterplot with marker color corresponding to RGB values

I have loaded a picture into a numpy array using mahotas.

import mahotas
img = mahotas.imread('test.jpg')

Each pixel in img is represented by an array of RGB values:

img[1,1] = [254, 200, 189]

I have made a 3D scatterplot of R values on one axis, G values on the 2nd axis and B values on the third axis. This is no problem:

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
for i in range(1,img.shape[1]+1):
    xs = img[i,1][0]
    ys = img[i,1][1]
    zs = img[i,1][2]
    ax.scatter(xs, ys, zs, c='0.5', marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

(I'm just plotting the first column of the image for the time being).

How can I color each of the scatterplot dots by the color of each image pixel? i.e. I guess I would like to color the dots by their RGB value, but I'm not sure if this is possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can do this, but it needs to be done through a separate mechanism than the c argument. In a nutshell, use facecolors=rgb_array.


First off, let me explain what's going on. The Collection that scatter returns has two "systems" (for lack of a better term) for setting colors.

If you use the c argument, you're setting the colors through the ScalarMappable "system". This specifies that the colors should be controlled by applying a colormap to a single variable. (This is the set_array method of anything that inherits from ScalarMappable.)

In addition to the ScalarMappable system, the colors of a collection can be set independently. In that case, you'd use the facecolors kwarg.


As a quick example, these points will have randomly specified rgb colors:

import matplotlib.pyplot as plt
import numpy as np

x, y = np.random.random((2, 10))
rgb = np.random.random((10, 3))

fig, ax = plt.subplots()
ax.scatter(x, y, s=200, facecolors=rgb)
plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...