Extreme Basics: отображение массива в виде изображения (2D или 3D) - PullRequest
1 голос
/ 13 апреля 2019

Я совершенно новый для Numpy, и я не использовал Python почти 8 лет [поэтому лучше предположить, что я тоже совершенно новый для Python].

Я пытаюсь отобразить двумерный массив в виде цветного изображения.Я хотел бы иметь возможность делать это и с 3-мерными массивами.

Для контекста я хотел бы отобразить этот массив ( массив с буквами ) с такими цветами: ( массив с цветами )

На втором шаге можно сделать вращающуюся фигуру, которая будет отображать трехмерный массив (по существу, как массив 1 выше, но с дополнительнымИзмерение ABCD, создание троек, таких как ABC, ABD, ACD и т. Д. Вместо пар, таких как AB, AC, AD и т. Д.).

Ответы [ 2 ]

0 голосов
/ 14 апреля 2019

В ответ на Асмуса: Это действительно хорошее начало. Я пытался взять ваш код и изменить его, но, к сожалению, что-то пошло не так. Некоторые клетки не те цвета, о которых я им говорю.

Мне также любопытно, возможно ли сделать трехмерную версию этого. Это будет иметь трехмерные ячейки разных цветов, каждая ячейка представляет различную трехбуквенную перестановку, где две ячейки имеют одинаковый цвет, если они содержат одинаковые 3 буквы.

#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

### create a dictionary with:
#   dictionary keys: will be used as color index
#   "name": "AB" <-- the text value
#   "color": "#ff0000" <-- a hex color value to represent each square
#   "coordinate": [1,0] <-- coordinates as x in (0,1,2) 
#                           and y-index (0,1) : where to plot this entry

white = "#ffffff"
grey = "#cecece"
red = "#ff0000"
green = "#00ff00"
purple = "#ccbbee"
pink = "#ffaabb"
dataDict={
    1:{"name":"A",
    "color":white,
    "coordinate": [0, 1]},
    2:{"name":"B",
    "color":white,
    "coordinate": [0, 2]},
    3:{"name":"C",
    "color":white,
    "coordinate": [0, 3]},
    4:{"name":"A",
    "color":white,
    "coordinate": [1, 0]},
    5:{"name":"B",
    "color":white,
    "coordinate": [2, 0]},
    6:{"name":"C",
    "color":white,
    "coordinate": [3, 0]},

    7:{"name":"AA",
    "color":grey,
    "coordinate":[1,1]},

    8:{"name":"AB",
    "color":green,
    "coordinate":[2,1]},

    9:{"name":"AC",
    "color":pink,
    "coordinate":[3,1]},

    10:{"name":"BA",
    "color":green,
    "coordinate":[1,2]},

    11:{"name":"BB",
    "color":grey,
    "coordinate":[2,2]},

    12:{"name":"BC",
    "color":purple,
    "coordinate":[3,2]},

    13:{"name":"CA",
    "color":pink,
    "coordinate":[1,3]},

    14:{"name":"CB",
    "color":purple,
    "coordinate":[2,3]},

    15:{"name":"CC",
    "color":grey,
    "coordinate":[3,3]}
}

### define the size of your array in x- and y-direction
x_size=4
y_size=4

### create an empty image array of proper dimensions
img_array = np.zeros((y_size,x_size))

### iterate over the dictionary: 
#   - looking up the color index (0-5)
#   - and store it in the img_array
for i,v in dataDict.items():
    [xi,yi]=v["coordinate"]
    img_array[yi,xi] = i

### create a colormap which 
#   maps the dictionary keys (0-5) to the respective color value
cmap = ListedColormap([v["color"] for i,v in dataDict.items()])

### create a figure and subplot
fig,ax=plt.subplots(1,1)
### tell the subplot to show the image "img_array" using the colormap "cmap"
ax.imshow(img_array,cmap=cmap,zorder=1,origin="upper")

#### iterate over the dictionary, get the coordiantes and names, and place text
for i,v in dataDict.items():
    print(i,v["coordinate"][0],v["coordinate"][1])
    ax.text(v["coordinate"][0],v["coordinate"][1],v["name"],zorder=2,)

### shwo the plot    
plt.show()
0 голосов
/ 13 апреля 2019

Важно отметить: Я не полностью уверен Правильно ли я понял ваш запрос;поэтому сначала я дам ответ, который охватывает ваш вопрос только частично.Я улучшу это позже, как только вы дадите мне знать, что я иду в правильном направлении.

#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

### create a dictionary with:
#   dictionary keys: will be used as color index
#   "name": "AB" <-- the text value
#   "color": "#ff0000" <-- a hex color value to represent each square
#   "coordinate": [1,0] <-- coordinates as x in (0,1,2) 
#                           and y-index (0,1) : where to plot this entry
dataDict={
    0:{"name":"AA",
    "color":"#ff0000",
    "coordinate":[0,0]},
    1:{"name":"AB",
    "color":"#00ff00",
    "coordinate":[1,0]},
    2:{"name":"AC",
    "color":"#0000ff",
    "coordinate":[2,0]},
    3:{"name":"BA",
    "color":"#0fff0f",
    "coordinate":[0,1]},
    4:{"name":"BB",
    "color":"#cecece",
    "coordinate":[1,1]},
    5:{"name":"BC",
    "color":"#000033",
    "coordinate":[2,1]},
}

### define the size of your array in x- and y-direction
x_size=3
y_size=2

### create an empty image array of proper dimensions
img_array = np.zeros((y_size,x_size))

### iterate over the dictionary: 
#   - looking up the color index (0-5)
#   - and store it in the img_array
for i,v in dataDict.items():
    [xi,yi]=v["coordinate"]
    img_array[yi,xi] = i

### create a colormap which 
#   maps the dictionary keys (0-5) to the respective color value
cmap = ListedColormap([v["color"] for i,v in dataDict.items()])

### create a figure and subplot
fig,ax=plt.subplots(1,1)
### tell the subplot to show the image "img_array" using the colormap "cmap"
ax.imshow(img_array,cmap=cmap,zorder=1,origin="upper")

#### iterate over the dictionary, get the coordiantes and names, and place text
for i,v in dataDict.items():
    print(i,v["coordinate"][0],v["coordinate"][1])
    ax.text(v["coordinate"][0],v["coordinate"][1],v["name"],zorder=2,)

### shwo the plot    
plt.show()
...