简体   繁体   English

将Matlab(八度)组着色代码转换为python(numpy,pyplot)

[英]Translating Matlab (Octave) group coloring code into python (numpy, pyplot)

I want to translate the following group coloring octave function to python and use it with pyplot . 我想将以下组着色八度音函数转换为python ,并与pyplot一起使用

Function input: 功能输入:
x - Data matrix (mxn) x-数据矩阵(mxn)
a - A parameter. 一个 -一个参数。
index - A vector of size "m" with values in range [: a] index-大小为“ m”的向量,其值在[:a]范围内
(For example if a = 4, index can be [random.choice(range(4)) for i in range(m)] (例如,如果a = 4,则索引可以是[range(m)中i的[random.choice(range(4)))]

The values in "index" indicate the number of the group the "m"th data point belongs to. “索引”中的值指示第“ m”个数据点所属的组的编号。 The function should plot all the data points from x and color them in different colors (Number of different colors is "a"). 该函数应绘制来自x的所有数据点,并以不同的颜色为其着色(不同颜色的数量为“ a”)。

The function in octave: 八度的功能:

p = hsv(a); % This is a x 3 metrix
colors = p(index, :); % ****This is m x 3 metrix****
scatter(X(:,1), X(:,2), 10, colors);

I couldn't find a function like hsv in python, so I wrote it myself (I think I did..): 我在python中找不到类似hsv的函数,所以我自己写了它(我想是的。):

 p = colors.hsv_to_rgb(numpy.column_stack((
numpy.linspace(0, 1, a), numpy.ones((a ,2)) )) )

But I can't figure out how to do the matrix selection p(index, :) in python (numpy). 但是我不知道如何在python(numpy)中进行矩阵选择p(index,:)。 Specially because the size of "index" is bigger then "a". 特别是因为“索引”的大小比“ a”大。

Thanks in advance for your help. 在此先感谢您的帮助。

So, you want to take an mx 3 of HSV values, and convert each row to RGB ? 因此,您要获取mx 3HSV值,并将每行转换为RGB

import numpy as np
import colorsys
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])

def to_hsv(x):
    return colorsys.rgb_to_hsv(*x)

#Apply the to_hsv function to each matrix row.
print np.apply_along_axis(to_hsv, axis=1, arr=mymatrix)

This produces: 这将产生:

[[  0.5   0.   13. ]
 [  0.5   0.   23. ]
 [  0.5   0.   33. ]]

Follow through on your comment: 遵循您的评论:

If I understand you have a matrix p that is an ax 3 matrix, and you want to randomly select rows from the matrix over and over again, until you have a new matrix that is mx 3 ? 据我了解,您有一个矩阵p ,它是一个ax 3轴矩阵,您想一次又一次地从矩阵中随机选择行,直到您有了一个新的矩阵,即mx 3 ?。

Ok. 好。 Let's say you have a matrix p defined as follows: 假设您有一个定义如下的矩阵p

a = 5
p = np.random.randint(5, size=(a, 3))

Now, make a list of random integers between the range 0 -> 3 (index starts at 0 and ends to a-1 ), That is m in length: 现在,创建一个介于0 -> 3之间的随机整数列表(索引从0开始到a-1结束),长度为m

m = 20
index = np.random.randint(a, size=m)

Now access the right indexes and plug them into a new matrix: 现在访问正确的索引并将其插入新矩阵:

p_prime = np.matrix([p[i] for i in index])

Produces a 20 x 3 matrix. 产生一个20 x 3矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM