GVKun编程网logo

使用Python创建3D数组(python创建三维数组)

8

本文将带您了解关于使用Python创建3D数组的新内容,同时我们还将为您解释python创建三维数组的相关知识,另外,我们还将为您提供关于Mapnik教程-使用Python创建地图、python–2D

本文将带您了解关于使用Python创建3D数组的新内容,同时我们还将为您解释python创建三维数组的相关知识,另外,我们还将为您提供关于Mapnik教程-使用Python创建地图、python – 2D数组每列的外积,形成一个3D数组 – NumPy、python – Numpy 3d数组映射操作、python – 从numpy中的(n)D数组中选择(n-1)D数组的实用信息。

本文目录一览:

使用Python创建3D数组(python创建三维数组)

使用Python创建3D数组(python创建三维数组)

我想在Python(2.7)中创建一个3D数组,以便像这样使用:

distance[i][j][k]

数组的大小应该是我拥有的变量的大小。(n n n)

我尝试使用:

distance = [[[]*n]*n]

但这似乎不起作用。

我只能使用默认库,并且乘法(即[[0]*n]*n)的方法将不起作用,因为它们链接到相同的指针,并且我需要所有值都是单独的

Mapnik教程-使用Python创建地图

Mapnik教程-使用Python创建地图

Mapnik教程-使用Python创建地图

Tutorial 1 -- Getting started in Python

Overview

This tutorial will ensure that Mapnik and its Python bindings are properly installed and introduce you to some of the basic programming concepts for Mapnik.

Step 1: check installation

Make sure you have mapnik installed. You should be able to open a terminal and type:

mapnik-config -v # should return a version number.

This tutorial expects Mapnik 2.x or greater. Older versions do not provide the mapnik-config program, so we recommend upgrading.

Please note that if you are using mapnik 2.0.0 then you will need to adjust the "mapnik" module name to "mapnik2" in the Python commands. Refer to mapnik2 for details of the naming convention.

Please also note that unlike Mapnik 2.x, version 3.x does not include Python bindings anymore. You can find the new Python bindings here.

Next test the Python bindings. You should be able to open a terminal and type:

python -c "import mapnik;print mapnik.__file__" # should return the path to the python bindings and no errors

If the above does not work (e.g. throws an ImportError) then please go back and ensure Mapnik is properly installed. If you need help, sign up for the mailing list to ask questions or join the #mapnik room on freenode IRC

Step 2

Now, we need some data to render. Let''s use a shapefile of world border polygons from http://naturalearthdata.com. Download the data from this wiki''s local cache here or directly from the Natural Earth Data site. Unzip the archive in an easily accessible location of your choosing. In Step 3 we will be referencing the path to this shapefile in Python code, so make sure you know where you put it.

Once unzipped, you should see four files like:

ne_110m_admin_0_countries.shp
ne_110m_admin_0_countries.shx
ne_110m_admin_0_countries.dbf
ne_110m_admin_0_countries.prj

To download and unzip on the command line with the do:

wget https://github.com/mapnik/mapnik/wiki/data/110m-admin-0-countries.zip
unzip 110m-admin-0-countries.zip # creates ne_110m_admin_0_countries.shp

Step 3

Now we''re going to program in Python and Mapnik, using sample code and the Python interpreter.

The idea here is not that you have to interact with Mapnik via Python, but that this is a good way to build foundational skills for how Mapnik works.

So, let''s begin! Open a Python interpreter simply by typing in your terminal:

python

The code below can be pasted into your interpreter. Ideally paste line by line so you can confirm each step is working. The commented lines (#) should be able to be pasted without trouble, but depending on your interpreter setting may cause errors.

Import Mapnik

Import the Mapnik Python bindings:

import mapnik

Create a Map

m = mapnik.Map(600,300) # create a map with a given width and height in pixels# note: m.srs will default to ''+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs''# the ''map.srs'' is the target projection of the map and can be whatever you wish m.background = mapnik.Color(''steelblue'') # set background colour to ''steelblue''.

Create a Style

Create the Styles which determines how the data is rendered:

s = mapnik.Style() # style object to hold rulesr = mapnik.Rule() # rule object to hold symbolizers# to fill a polygon we create a PolygonSymbolizerpolygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(''#f2eff9''))
r.symbols.append(polygon_symbolizer) # add the symbolizer to the rule object# to add outlines to a polygon we create a LineSymbolizerline_symbolizer = mapnik.LineSymbolizer(mapnik.Color(''rgb(50%,50%,50%)''),0.1)
r.symbols.append(line_symbolizer) # add the symbolizer to the rule objects.rules.append(r) # now add the rule to the style and we''re done

And add the Style to the Map:

m.append_style(''My Style'',s) # Styles are given names only as they are applied to the map

Create a Datasource

In Step 2 above you should have downloaded a sample shapefile of polygons of world countries. We are now going to load that into a mapnik.Datasource object in Python.

If your Python interpreter was launched from the same directory as you downloaded the natural earth shapefile to you should be able to use a relative path to create the datasource like:

ds = mapnik.Shapefile(file=''ne_110m_admin_0_countries.shp'')

Otherwise use an absolute path (exchanging /Users/dane/Downloads/ for the correct path on your machine):

ds = mapnik.Shapefile(file=''/Users/dane/Downloads/ne_110m_admin_0_countries.shp'')

Note: optionally (to learn about your data) you can call the envelope() function off the datasource object to see the full coordinate bounds of the data:

>>> ds.envelope()
Box2d(-180.0,-90.0,180.0,83.64513)

That shows the minx, miny, maxx, and maxy of the data. Because the above coordinates are between -180 and 180 for the x or longitude values and -90 and 90 for the y or latitude values we know this data is in geographic coordinates and uses degrees for units - a pretty good indication this is WGS84 (aka EPSG:4326). This specific shapefile also stores this projection information as a WKT string in the ne_110m_admin_0_countries.prj file. See the layer.srs value below for why this matters.

Create a Layer

Mapnik Layers are basically containers around datasources, that store useful properties. Lets now create a Layer object and add the datasource to it.

layer = mapnik.Layer(''world'') # new layer called ''world'' (we could name it anything)# note: layer.srs will default to ''+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs''

Note: the ''layer.srs'' is the source projection of the Datasource and must match the projection of the coordinates of that data or else your map will likely be blank. Mapnik uses Proj.4 strings to specify the spatial references system. In this case, the default srs Mapnik assumes (+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs) happens to match the projection of the data. When this is not the case you must set the layer.srs to the correct value (which is beyond the scope of this tutorial).

Now attach the datasource to the layer, and reference:

layer.datasource = ds

Lastly, we need to make sure the style we created above (and attached to the map) is also applied to the layer, by its string reference:

layer.styles.append(''My Style'')

Prepare the Map for rendering

This step is critical. Finally add the layer to the map and zoom to the full extent of the data layer (using zoom_all which will calculate the cumulative extent of all layers attached to the map). If you do not zoom the Map to the extent of the layer(s), then the rendered output will be blank.

m.layers.append(layer)
m.zoom_all()

Render your map

Finish up by rendering your map image:

# Write the data to a png image called world.png in the current directorymapnik.render_to_file(m,''world.png'', ''png'')# Exit the Python interpreterexit() # or ctrl-d

Then back in your normal shell type:

# On a macopen world.png# On windowsstart world.png

Or navigate to your base directory and open world.png and the result should look like this: ![world.png]

Step 4

The next logical step is to run that same code all at once as a Python script from your shell/terminal (rather than pasted into the Python interpreter line-by-line). This way you will be able to modify and experiment with the settings, then simply re-run the script.

So, create a blank text file called world.py.

Make it executable:

chmod +x world.py

Then add a line at the top of the script like:

#!/usr/bin/env python

Finally, append the entire text below and save the file.

import mapnik
m = mapnik.Map(600,300)
m.background = mapnik.Color(''steelblue'')
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(''#f2eff9''))
r.symbols.append(polygon_symbolizer)
line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(''rgb(50%,50%,50%)''),0.1)
r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style(''My Style'',s)
ds = mapnik.Shapefile(file=''ne_110m_admin_0_countries.shp'')
layer = mapnik.Layer(''world'')
layer.datasource = ds
layer.styles.append(''My Style'')
m.layers.append(layer)
m.zoom_all()
mapnik.render_to_file(m,''world.png'', ''png'')print "rendered image to ''world.png''"
  • Don''t forget to ensure the correct path to your ne_110m_admin_0_countries.shp shapefile.

  • Mapnik accepts both the absolute path to your data as well as the relative path (Same goes for the path to where you want to save your file)

Finally run the script with the command:

./world.py # You must be in the same directory as you saved the script
  • Note: if you re-run this script it will will re-write over the world.png map.

  • Now you can easily open the script in a separate text editor and try changing the dimensions, colors, or datasource (remember to use the correct srs if you change the datasource).


python – 2D数组每列的外积,形成一个3D数组 – NumPy

python – 2D数组每列的外积,形成一个3D数组 – NumPy

令X为M×N矩阵.将xi表示为X的第i列.我想创建由M×M矩阵xi.dot(xi.T)组成的3维N×M×M阵列.

我怎么能用numpy最优雅地做到这一点?是否可以仅使用矩阵运算,没有循环?

解决方法

broadcasting的一种方法 –
X.T[:,:,None]*X.T[:,None]

另一个有广播和交换轴后 –

(X[:,None,:]*X).swapaxes(0,2)

另一个广播和之后的多维转置 –

(X[:,:]*X).T

使用np.einsum的另一种方法,如果从循环代码转换,可能就迭代器而言更直观的思考 –

np.einsum('ij,kj->jik',X,X)

所有这些方法的基本思想是我们展开最后一个轴,使元素相乘相互保持第一轴对齐.我们通过将X扩展到两个3D阵列版本来实现这种相互对立的过程.

python – Numpy 3d数组映射操作

python – Numpy 3d数组映射操作

现在我有一个三维的np.array [身高,体重,3]. (这是一张图片)我想实现一个RGB – > YUV算法本身 RGB2YUV.然而,从每个像素迭代并应用变换太慢.

for x in xrange(height):
    for y in xrange(weight):
          img[x,y] = mat_1 * img[x,y]

有没有办法使用一些实现这个的built_in方法?

解决方法

这似乎是 np.einsum的一个很好的用例:

yuv_image = np.einsum(''kl,ijl->ijk'',transformation_matrix,rgb_image)

一旦你把它写在一张纸上,就很容易想出这些指数.

示例显示两种方法的值相等:

>>> rgb_image = np.random.rand(2*4*3).reshape(2,4,3)
>>> transformation_matrix = np.random.rand(9).reshape(3,3)
>>> z = np.empty_like(rgb_image)
>>> for x in range(rgb_image.shape[0]):
...     for y in range(rgb_image.shape[1]):
...         z[x,y] = np.dot(transformation_matrix,rgb_image[x,y,:])
...
>>> np.allclose(z,np.einsum(''kl,rgb_image))
True

python – 从numpy中的(n)D数组中选择(n-1)D数组

python – 从numpy中的(n)D数组中选择(n-1)D数组

让我们以3D阵列为例.或者是一个易于可视化的立方体.

我想选择那个立方体的所有面孔.我想将其概括为任意维度.

我还想在多维数据集中添加/删除面(长方体),并将其推广到任意维度.

我知道,对于每个固定数量的维度,你可以做数组[:,:,0],数组[-1,]我想知道如何推广到任意维度以及如何轻松迭代所有面.

最佳答案
得到一张脸:

def get_face(M,dim,front_side):
    if front_side:
        side = 0
    else:
        side = -1
    index = tuple(side if i == dim else slice(None) for i in range(M.ndim))
    return M[index]

要添加面部(未经测试):

def add_face(M,new_face,front_side):
    #assume sizes match up correctly
    if front_side:
        return np.concatenate((new_face,M),dim)
    else:
        return np.concatenate((M,new_face),dim)

要删除一张脸:

def remove_face(M,front_side):
    if front_side:
        dim_slice = slice(1,None)
    else:
        dim_slice = slice(None,-1)
    index = tuple(dim_slice if i == dim else slice(None) for i in range(M.ndim))
    return M[index]

迭代所有面孔:

def iter_faces(M):
    for dim in range(M.ndim):
        for front_side in (True,False):
            yield get_face(M,front_side)

一些快速测试:

In [18]: M = np.arange(27).reshape((3,3,3))
In [19]: for face in iter_faces(M): print face
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[18 19 20]
 [21 22 23]
 [24 25 26]]
[[ 0  1  2]
 [ 9 10 11]
 [18 19 20]]
[[ 6  7  8]
 [15 16 17]
 [24 25 26]]
[[ 0  3  6]
 [ 9 12 15]
 [18 21 24]]
[[ 2  5  8]
 [11 14 17]
 [20 23 26]]

关于使用Python创建3D数组python创建三维数组的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Mapnik教程-使用Python创建地图、python – 2D数组每列的外积,形成一个3D数组 – NumPy、python – Numpy 3d数组映射操作、python – 从numpy中的(n)D数组中选择(n-1)D数组等相关知识的信息别忘了在本站进行查找喔。

本文标签: