【问题标题】:"m x n" dimensional gradient-style array in PythonPython中的“m x n”维梯度样式数组
【发布时间】:2016-04-08 20:07:04
【问题描述】:

我签了 gradient descent using python and numpy 但这并没有解决我的问题。

我正在尝试熟悉image-processing,并且我想生成一些测试数组以在 Python 中进行处理。

是否有一种方法(如 np.arange)来创建一个 m x n 数组,其中内部条目形成某种类型的渐变?

我做了一个用于生成所需输出的简单方法的示例。

请原谅我对渐变一词的概括性,我使用它的简单含义是颜色的平滑过渡。

#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt

#Set up parameters
m = 15
n = 10
A_placeholder = np.zeros((m,n))
V_m = np.arange(0,m).astype(np.float32)
V_n = np.arange(0,n).astype(np.float32)

#Iterate through combinations
for i in range(m):
    m_i = V_m[i]
    for j in range(n):
        n_j = V_n[j]
        A_placeholder[i,j] = m_i * n_j #Some combination

#Relabel
A_gradient = A_placeholder
A_placeholder = None

#Print data
print A_gradient
#[[   0.    0.    0.    0.    0.    0.    0.    0.    0.    0.]
 [   0.    1.    2.    3.    4.    5.    6.    7.    8.    9.]
 [   0.    2.    4.    6.    8.   10.   12.   14.   16.   18.]
 [   0.    3.    6.    9.   12.   15.   18.   21.   24.   27.]
 [   0.    4.    8.   12.   16.   20.   24.   28.   32.   36.]
 [   0.    5.   10.   15.   20.   25.   30.   35.   40.   45.]
 [   0.    6.   12.   18.   24.   30.   36.   42.   48.   54.]
 [   0.    7.   14.   21.   28.   35.   42.   49.   56.   63.]
 [   0.    8.   16.   24.   32.   40.   48.   56.   64.   72.]
 [   0.    9.   18.   27.   36.   45.   54.   63.   72.   81.]
 [   0.   10.   20.   30.   40.   50.   60.   70.   80.   90.]
 [   0.   11.   22.   33.   44.   55.   66.   77.   88.   99.]
 [   0.   12.   24.   36.   48.   60.   72.   84.   96.  108.]
 [   0.   13.   26.   39.   52.   65.   78.   91.  104.  117.]
 [   0.   14.   28.   42.   56.   70.   84.   98.  112.  126.]]

#Show Image
plt.imshow(A_gradient)
plt.show()

我试过np.gradient,但它没有给我想要的输出。

#print np.gradient(np.array([V_m,V_n]))
#Traceback (most recent call last):
#    File "Untitled.py", line 19, in <module>
#        print np.gradient(np.array([V_m,V_n]))
#    File "/Users/Mu/anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py", line 1458, in gradient
#        out[slice1] = (y[slice2] - y[slice3])
#ValueError: operands could not be broadcast together with shapes (10,) (15,) 

【问题讨论】:

    标签: python arrays numpy image-processing gradient


    【解决方案1】:
    A_placeholder[i,j] = m_i * n_j
    

    任何类似的操作都可以使用broadcasting在numpy中表达

    A = np.arange(m)[:, None] * np.arange(n)[None, :]
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多